MDL-63903 core_message: fix bug with shim code in index.php
[moodle.git] / message / tests / externallib_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * External message functions unit tests
19  *
20  * @package    core_message
21  * @category   external
22  * @copyright  2012 Jerome Mouneyrac
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
30 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
31 require_once($CFG->dirroot . '/message/externallib.php');
33 use \core_message\tests\helper as testhelper;
35 class core_message_externallib_testcase extends externallib_advanced_testcase {
37     /**
38      * Tests set up
39      */
40     protected function setUp() {
41         global $CFG;
43         require_once($CFG->dirroot . '/message/lib.php');
44     }
46     /**
47      * Send a fake message.
48      *
49      * {@link message_send()} does not support transaction, this function will simulate a message
50      * sent from a user to another. We should stop using it once {@link message_send()} will support
51      * transactions. This is not clean at all, this is just used to add rows to the table.
52      *
53      * @param stdClass $userfrom user object of the one sending the message.
54      * @param stdClass $userto user object of the one receiving the message.
55      * @param string $message message to send.
56      * @param int $notification is the message a notification.
57      * @param int $time the time the message was sent
58      */
59     protected function send_message($userfrom, $userto, $message = 'Hello world!', $notification = 0, $time = 0) {
60         global $DB;
62         if (empty($time)) {
63             $time = time();
64         }
66         if ($notification) {
67             $record = new stdClass();
68             $record->useridfrom = $userfrom->id;
69             $record->useridto = $userto->id;
70             $record->subject = 'No subject';
71             $record->fullmessage = $message;
72             $record->smallmessage = $message;
73             $record->timecreated = $time;
75             return $DB->insert_record('notifications', $record);
76         }
78         if (!$conversationid = \core_message\api::get_conversation_between_users([$userfrom->id, $userto->id])) {
79             $conversation = \core_message\api::create_conversation(
80                 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
81                 [
82                     $userfrom->id,
83                     $userto->id
84                 ]
85             );
86             $conversationid = $conversation->id;
87         }
89         // Ok, send the message.
90         $record = new stdClass();
91         $record->useridfrom = $userfrom->id;
92         $record->conversationid = $conversationid;
93         $record->subject = 'No subject';
94         $record->fullmessage = $message;
95         $record->smallmessage = $message;
96         $record->timecreated = $time;
98         return $DB->insert_record('messages', $record);
99     }
101     /**
102      * Test send_instant_messages.
103      */
104     public function test_send_instant_messages() {
105         global $DB, $USER;
107         $this->resetAfterTest();
109         // Transactions used in tests, tell phpunit use alternative reset method.
110         $this->preventResetByRollback();
112         $user1 = self::getDataGenerator()->create_user();
113         $user2 = self::getDataGenerator()->create_user();
115         $this->setUser($user1);
117         // Create test message data.
118         $message1 = array();
119         $message1['touserid'] = $user2->id;
120         $message1['text'] = 'the message.';
121         $message1['clientmsgid'] = 4;
122         $messages = array($message1);
124         $sentmessages = core_message_external::send_instant_messages($messages);
125         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
126         $this->assertEquals(
127             get_string('usercantbemessaged', 'message', fullname(\core_user::get_user($message1['touserid']))),
128             array_pop($sentmessages)['errormessage']
129         );
131         // Add the user1 as a contact.
132         \core_message\api::add_contact($user1->id, $user2->id);
134         // Send message again. Now it should work properly.
135         $sentmessages = core_message_external::send_instant_messages($messages);
136         // We need to execute the return values cleaning process to simulate the web service server.
137         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
139         $sentmessage = reset($sentmessages);
141         $sql = "SELECT m.*, mcm.userid as useridto
142                  FROM {messages} m
143            INNER JOIN {message_conversations} mc
144                    ON m.conversationid = mc.id
145            INNER JOIN {message_conversation_members} mcm
146                    ON mcm.conversationid = mc.id
147                 WHERE mcm.userid != ?
148                   AND m.id = ?";
149         $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
151         // Confirm that the message was inserted correctly.
152         $this->assertEquals($themessage->useridfrom, $user1->id);
153         $this->assertEquals($themessage->useridto, $message1['touserid']);
154         $this->assertEquals($themessage->smallmessage, $message1['text']);
155         $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
156     }
158     /**
159      * Test send_instant_messages to a user who has blocked you.
160      */
161     public function test_send_instant_messages_blocked_user() {
162         global $DB;
164         $this->resetAfterTest();
166         // Transactions used in tests, tell phpunit use alternative reset method.
167         $this->preventResetByRollback();
169         $user1 = self::getDataGenerator()->create_user();
170         $user2 = self::getDataGenerator()->create_user();
172         $this->setUser($user1);
174         \core_message\api::block_user($user2->id, $user1->id);
176         // Create test message data.
177         $message1 = array();
178         $message1['touserid'] = $user2->id;
179         $message1['text'] = 'the message.';
180         $message1['clientmsgid'] = 4;
181         $messages = array($message1);
183         $sentmessages = core_message_external::send_instant_messages($messages);
184         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
186         $sentmessage = reset($sentmessages);
188         $this->assertEquals(get_string('usercantbemessaged', 'message', fullname($user2)), $sentmessage['errormessage']);
190         $this->assertEquals(0, $DB->count_records('messages'));
191     }
193     /**
194      * Test send_instant_messages when sending a message to a non-contact who has blocked non-contacts.
195      */
196     public function test_send_instant_messages_block_non_contacts() {
197         global $DB;
199         $this->resetAfterTest(true);
201         // Transactions used in tests, tell phpunit use alternative reset method.
202         $this->preventResetByRollback();
204         $user1 = self::getDataGenerator()->create_user();
205         $user2 = self::getDataGenerator()->create_user();
207         $this->setUser($user1);
209         // Set the user preference so user 2 does not accept messages from non-contacts.
210         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2);
212         // Create test message data.
213         $message1 = array();
214         $message1['touserid'] = $user2->id;
215         $message1['text'] = 'the message.';
216         $message1['clientmsgid'] = 4;
217         $messages = array($message1);
219         $sentmessages = core_message_external::send_instant_messages($messages);
220         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
222         $sentmessage = reset($sentmessages);
224         $this->assertEquals(get_string('usercantbemessaged', 'message', fullname($user2)), $sentmessage['errormessage']);
226         $this->assertEquals(0, $DB->count_records('messages'));
227     }
229     /**
230      * Test send_instant_messages when sending a message to a contact who has blocked non-contacts.
231      */
232     public function test_send_instant_messages_block_non_contacts_but_am_contact() {
233         global $DB, $USER;
235         $this->resetAfterTest(true);
237         // Transactions used in tests, tell phpunit use alternative reset method.
238         $this->preventResetByRollback();
240         $user1 = self::getDataGenerator()->create_user();
241         $user2 = self::getDataGenerator()->create_user();
243         $this->setUser($user1);
245         // Set the user preference so user 2 does not accept messages from non-contacts.
246         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2);
248         \core_message\api::add_contact($user1->id, $user2->id);
250         // Create test message data.
251         $message1 = array();
252         $message1['touserid'] = $user2->id;
253         $message1['text'] = 'the message.';
254         $message1['clientmsgid'] = 4;
255         $messages = array($message1);
257         $sentmessages = core_message_external::send_instant_messages($messages);
258         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
260         $sentmessage = reset($sentmessages);
262         $sql = "SELECT m.*, mcm.userid as useridto
263                  FROM {messages} m
264            INNER JOIN {message_conversations} mc
265                    ON m.conversationid = mc.id
266            INNER JOIN {message_conversation_members} mcm
267                    ON mcm.conversationid = mc.id
268                 WHERE mcm.userid != ?
269                   AND m.id = ?";
270         $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
272         // Confirm that the message was inserted correctly.
273         $this->assertEquals($themessage->useridfrom, $user1->id);
274         $this->assertEquals($themessage->useridto, $message1['touserid']);
275         $this->assertEquals($themessage->smallmessage, $message1['text']);
276         $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
277     }
279     /**
280      * Test send_instant_messages with no capabilities
281      */
282     public function test_send_instant_messages_no_capability() {
283         global $DB;
285         $this->resetAfterTest(true);
287         // Transactions used in tests, tell phpunit use alternative reset method.
288         $this->preventResetByRollback();
290         $user1 = self::getDataGenerator()->create_user();
291         $user2 = self::getDataGenerator()->create_user();
293         $this->setUser($user1);
295         // Unset the required capabilities by the external function.
296         $contextid = context_system::instance()->id;
297         $userrole = $DB->get_record('role', array('shortname' => 'user'));
298         $this->unassignUserCapability('moodle/site:sendmessage', $contextid, $userrole->id);
300         // Create test message data.
301         $message1 = array();
302         $message1['touserid'] = $user2->id;
303         $message1['text'] = 'the message.';
304         $message1['clientmsgid'] = 4;
305         $messages = array($message1);
307         $this->expectException('required_capability_exception');
308         core_message_external::send_instant_messages($messages);
309     }
311     /**
312      * Test send_instant_messages when messaging is disabled.
313      */
314     public function test_send_instant_messages_messaging_disabled() {
315         global $CFG;
317         $this->resetAfterTest(true);
319         // Transactions used in tests, tell phpunit use alternative reset method.
320         $this->preventResetByRollback();
322         $user1 = self::getDataGenerator()->create_user();
323         $user2 = self::getDataGenerator()->create_user();
325         $this->setUser($user1);
327         // Disable messaging.
328         $CFG->messaging = 0;
330         // Create test message data.
331         $message1 = array();
332         $message1['touserid'] = $user2->id;
333         $message1['text'] = 'the message.';
334         $message1['clientmsgid'] = 4;
335         $messages = array($message1);
337         $this->expectException('moodle_exception');
338         core_message_external::send_instant_messages($messages);
339     }
341     /**
342      * Test create_contacts.
343      */
344     public function test_create_contacts() {
345         $this->resetAfterTest(true);
347         $user1 = self::getDataGenerator()->create_user();
348         $user2 = self::getDataGenerator()->create_user();
349         $user3 = self::getDataGenerator()->create_user();
350         $user4 = self::getDataGenerator()->create_user();
351         $user5 = self::getDataGenerator()->create_user();
352         $this->setUser($user1);
354         // Adding a contact.
355         $return = core_message_external::create_contacts(array($user2->id));
356         $this->assertDebuggingCalled();
357         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
358         $this->assertEquals(array(), $return);
360         // Adding a contact who is already a contact.
361         $return = core_message_external::create_contacts(array($user2->id));
362         $this->assertDebuggingCalled();
363         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
364         $this->assertEquals(array(), $return);
366         // Adding multiple contacts.
367         $return = core_message_external::create_contacts(array($user3->id, $user4->id));
368         $this->assertDebuggingCalledCount(2);
369         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
370         $this->assertEquals(array(), $return);
372         // Adding a non-existing user.
373         $return = core_message_external::create_contacts(array(99999));
374         $this->assertDebuggingCalled();
375         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
376         $this->assertCount(1, $return);
377         $return = array_pop($return);
378         $this->assertEquals($return['warningcode'], 'contactnotcreated');
379         $this->assertEquals($return['itemid'], 99999);
381         // Adding contacts with valid and invalid parameters.
382         $return = core_message_external::create_contacts(array($user5->id, 99999));
383         $this->assertDebuggingCalledCount(2);
384         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
385         $this->assertCount(1, $return);
386         $return = array_pop($return);
387         $this->assertEquals($return['warningcode'], 'contactnotcreated');
388         $this->assertEquals($return['itemid'], 99999);
390         // Try to add a contact to another user, should throw an exception.
391         // All assertions must be added before this point.
392         $this->expectException('required_capability_exception');
393         core_message_external::create_contacts(array($user2->id), $user3->id);
394     }
396     /**
397      * Test delete_contacts.
398      */
399     public function test_delete_contacts() {
400         $this->resetAfterTest(true);
402         $user1 = self::getDataGenerator()->create_user();
403         $user2 = self::getDataGenerator()->create_user();
404         $user3 = self::getDataGenerator()->create_user();
405         $user4 = self::getDataGenerator()->create_user();
406         $user5 = self::getDataGenerator()->create_user();
407         $user6 = self::getDataGenerator()->create_user();
408         $this->setUser($user1);
410         \core_message\api::add_contact($user1->id, $user3->id);
411         \core_message\api::add_contact($user1->id, $user4->id);
412         \core_message\api::add_contact($user1->id, $user5->id);
413         \core_message\api::add_contact($user1->id, $user6->id);
415         // Removing a non-contact.
416         $return = core_message_external::delete_contacts(array($user2->id));
417         $this->assertNull($return);
419         // Removing one contact.
420         $return = core_message_external::delete_contacts(array($user3->id));
421         $this->assertNull($return);
423         // Removing multiple contacts.
424         $return = core_message_external::delete_contacts(array($user4->id, $user5->id));
425         $this->assertNull($return);
427         // Removing contact from unexisting user.
428         $return = core_message_external::delete_contacts(array(99999));
429         $this->assertNull($return);
431         // Removing mixed valid and invalid data.
432         $return = core_message_external::delete_contacts(array($user6->id, 99999));
433         $this->assertNull($return);
435         // Try to delete a contact of another user contact list, should throw an exception.
436         // All assertions must be added before this point.
437         $this->expectException('required_capability_exception');
438         core_message_external::delete_contacts(array($user2->id), $user3->id);
439     }
441     /**
442      * Test block_contacts.
443      */
444     public function test_block_contacts() {
445         $this->resetAfterTest(true);
447         $user1 = self::getDataGenerator()->create_user();
448         $user2 = self::getDataGenerator()->create_user();
449         $user3 = self::getDataGenerator()->create_user();
450         $user4 = self::getDataGenerator()->create_user();
451         $user5 = self::getDataGenerator()->create_user();
452         $this->setUser($user1);
454         \core_message\api::add_contact($user1->id, $user3->id);
455         \core_message\api::add_contact($user1->id, $user4->id);
456         \core_message\api::add_contact($user1->id, $user5->id);
458         // Blocking a contact.
459         $return = core_message_external::block_contacts(array($user2->id));
460         $this->assertDebuggingCalled();
461         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
462         $this->assertEquals(array(), $return);
464         // Blocking a contact who is already a contact.
465         $return = core_message_external::block_contacts(array($user2->id));
466         $this->assertDebuggingCalled();
467         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
468         $this->assertEquals(array(), $return);
470         // Blocking multiple contacts.
471         $return = core_message_external::block_contacts(array($user3->id, $user4->id));
472         $this->assertDebuggingCalledCount(2);
473         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
474         $this->assertEquals(array(), $return);
476         // Blocking a non-existing user.
477         $return = core_message_external::block_contacts(array(99999));
478         $this->assertDebuggingCalled();
479         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
480         $this->assertCount(1, $return);
481         $return = array_pop($return);
482         $this->assertEquals($return['warningcode'], 'contactnotblocked');
483         $this->assertEquals($return['itemid'], 99999);
485         // Blocking contacts with valid and invalid parameters.
486         $return = core_message_external::block_contacts(array($user5->id, 99999));
487         $this->assertDebuggingCalledCount(2);
488         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
489         $this->assertCount(1, $return);
490         $return = array_pop($return);
491         $this->assertEquals($return['warningcode'], 'contactnotblocked');
492         $this->assertEquals($return['itemid'], 99999);
494         // Try to block a contact of another user contact list, should throw an exception.
495         // All assertions must be added before this point.
496         $this->expectException('required_capability_exception');
497         core_message_external::block_contacts(array($user2->id), $user3->id);
498     }
500     /**
501      * Test unblock_contacts.
502      */
503     public function test_unblock_contacts() {
504         $this->resetAfterTest(true);
506         $user1 = self::getDataGenerator()->create_user();
507         $user2 = self::getDataGenerator()->create_user();
508         $user3 = self::getDataGenerator()->create_user();
509         $user4 = self::getDataGenerator()->create_user();
510         $user5 = self::getDataGenerator()->create_user();
511         $user6 = self::getDataGenerator()->create_user();
512         $this->setUser($user1);
514         \core_message\api::add_contact($user1->id, $user3->id);
515         \core_message\api::add_contact($user1->id, $user4->id);
516         \core_message\api::add_contact($user1->id, $user5->id);
517         \core_message\api::add_contact($user1->id, $user6->id);
519         // Removing a non-contact.
520         $return = core_message_external::unblock_contacts(array($user2->id));
521         $this->assertDebuggingCalled();
522         $this->assertNull($return);
524         // Removing one contact.
525         $return = core_message_external::unblock_contacts(array($user3->id));
526         $this->assertDebuggingCalled();
527         $this->assertNull($return);
529         // Removing multiple contacts.
530         $return = core_message_external::unblock_contacts(array($user4->id, $user5->id));
531         $this->assertDebuggingCalledCount(2);
532         $this->assertNull($return);
534         // Removing contact from unexisting user.
535         $return = core_message_external::unblock_contacts(array(99999));
536         $this->assertDebuggingCalled();
537         $this->assertNull($return);
539         // Removing mixed valid and invalid data.
540         $return = core_message_external::unblock_contacts(array($user6->id, 99999));
541         $this->assertDebuggingCalledCount(2);
542         $this->assertNull($return);
544         // Try to unblock a contact of another user contact list, should throw an exception.
545         // All assertions must be added before this point.
546         $this->expectException('required_capability_exception');
547         core_message_external::unblock_contacts(array($user2->id), $user3->id);
548         $this->assertDebuggingCalled();
549     }
551     /**
552      * Test getting contact requests.
553      */
554     public function test_get_contact_requests() {
555         $this->resetAfterTest();
557         $user1 = self::getDataGenerator()->create_user();
558         $user2 = self::getDataGenerator()->create_user();
559         $user3 = self::getDataGenerator()->create_user();
561         $this->setUser($user1);
563         // Block one user, their request should not show up.
564         \core_message\api::block_user($user1->id, $user3->id);
566         \core_message\api::create_contact_request($user2->id, $user1->id);
567         \core_message\api::create_contact_request($user3->id, $user1->id);
569         $requests = core_message_external::get_contact_requests($user1->id);
570         $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
572         $this->assertCount(1, $requests);
574         $request = reset($requests);
576         $this->assertEquals($user2->id, $request['id']);
577         $this->assertEquals($user2->picture, $request['picture']);
578         $this->assertEquals($user2->firstname, $request['firstname']);
579         $this->assertEquals($user2->lastname, $request['lastname']);
580         $this->assertEquals($user2->firstnamephonetic, $request['firstnamephonetic']);
581         $this->assertEquals($user2->lastnamephonetic, $request['lastnamephonetic']);
582         $this->assertEquals($user2->middlename, $request['middlename']);
583         $this->assertEquals($user2->alternatename, $request['alternatename']);
584         $this->assertEquals($user2->email, $request['email']);
585     }
587     /**
588      * Test getting contact requests with messaging disabled.
589      */
590     public function test_get_contact_requests_messaging_disabled() {
591         global $CFG;
593         $this->resetAfterTest();
595         // Create some skeleton data just so we can call the WS.
596         $user1 = self::getDataGenerator()->create_user();
598         $this->setUser($user1);
600         // Disable messaging.
601         $CFG->messaging = 0;
603         // Ensure an exception is thrown.
604         $this->expectException('moodle_exception');
605         core_message_external::get_contact_requests($user1->id);
606     }
608     /**
609      * Test getting contact requests with no permission.
610      */
611     public function test_get_contact_requests_no_permission() {
612         $this->resetAfterTest();
614         // Create some skeleton data just so we can call the WS.
615         $user1 = self::getDataGenerator()->create_user();
616         $user2 = self::getDataGenerator()->create_user();
617         $user3 = self::getDataGenerator()->create_user();
619         $this->setUser($user3);
621         // Ensure an exception is thrown.
622         $this->expectException('required_capability_exception');
623         core_message_external::create_contact_request($user1->id, $user2->id);
624     }
626     /**
627      * Test creating a contact request.
628      */
629     public function test_create_contact_request() {
630         global $CFG, $DB;
632         $this->resetAfterTest();
634         $user1 = self::getDataGenerator()->create_user();
635         $user2 = self::getDataGenerator()->create_user();
637         $this->setUser($user1);
639         // Allow users to message anyone site-wide.
640         $CFG->messagingallusers = 1;
642         $return = core_message_external::create_contact_request($user1->id, $user2->id);
643         $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
644         $this->assertEquals(array(), $return);
646         $request = $DB->get_records('message_contact_requests');
648         $this->assertCount(1, $request);
650         $request = reset($request);
652         $this->assertEquals($user1->id, $request->userid);
653         $this->assertEquals($user2->id, $request->requesteduserid);
654     }
656     /**
657      * Test creating a contact request when not allowed.
658      */
659     public function test_create_contact_request_not_allowed() {
660         global $CFG;
662         $this->resetAfterTest();
664         $user1 = self::getDataGenerator()->create_user();
665         $user2 = self::getDataGenerator()->create_user();
667         $this->setUser($user1);
669         $CFG->messagingallusers = 0;
671         $return = core_message_external::create_contact_request($user1->id, $user2->id);
672         $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
674         $warning = reset($return);
676         $this->assertEquals('user', $warning['item']);
677         $this->assertEquals($user2->id, $warning['itemid']);
678         $this->assertEquals('cannotcreatecontactrequest', $warning['warningcode']);
679         $this->assertEquals('You are unable to create a contact request for this user', $warning['message']);
680     }
682     /**
683      * Test creating a contact request with messaging disabled.
684      */
685     public function test_create_contact_request_messaging_disabled() {
686         global $CFG;
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();
694         $this->setUser($user1);
696         // Disable messaging.
697         $CFG->messaging = 0;
699         // Ensure an exception is thrown.
700         $this->expectException('moodle_exception');
701         core_message_external::create_contact_request($user1->id, $user2->id);
702     }
704     /**
705      * Test creating a contact request with no permission.
706      */
707     public function test_create_contact_request_no_permission() {
708         $this->resetAfterTest();
710         // Create some skeleton data just so we can call the WS.
711         $user1 = self::getDataGenerator()->create_user();
712         $user2 = self::getDataGenerator()->create_user();
713         $user3 = self::getDataGenerator()->create_user();
715         $this->setUser($user3);
717         // Ensure an exception is thrown.
718         $this->expectException('required_capability_exception');
719         core_message_external::create_contact_request($user1->id, $user2->id);
720     }
722     /**
723      * Test confirming a contact request.
724      */
725     public function test_confirm_contact_request() {
726         global $DB;
728         $this->resetAfterTest();
730         $user1 = self::getDataGenerator()->create_user();
731         $user2 = self::getDataGenerator()->create_user();
733         $this->setUser($user1);
735         \core_message\api::create_contact_request($user1->id, $user2->id);
737         $this->setUser($user2);
739         $return = core_message_external::confirm_contact_request($user1->id, $user2->id);
740         $return = external_api::clean_returnvalue(core_message_external::confirm_contact_request_returns(), $return);
741         $this->assertEquals(array(), $return);
743         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
745         $contact = $DB->get_records('message_contacts');
747         $this->assertCount(1, $contact);
749         $contact = reset($contact);
751         $this->assertEquals($user1->id, $contact->userid);
752         $this->assertEquals($user2->id, $contact->contactid);
753     }
755     /**
756      * Test confirming a contact request with messaging disabled.
757      */
758     public function test_confirm_contact_request_messaging_disabled() {
759         global $CFG;
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();
767         $this->setUser($user1);
769         // Disable messaging.
770         $CFG->messaging = 0;
772         // Ensure an exception is thrown.
773         $this->expectException('moodle_exception');
774         core_message_external::confirm_contact_request($user1->id, $user2->id);
775     }
777     /**
778      * Test confirming a contact request with no permission.
779      */
780     public function test_confirm_contact_request_no_permission() {
781         $this->resetAfterTest();
783         // Create some skeleton data just so we can call the WS.
784         $user1 = self::getDataGenerator()->create_user();
785         $user2 = self::getDataGenerator()->create_user();
786         $user3 = self::getDataGenerator()->create_user();
788         $this->setUser($user3);
790         // Ensure an exception is thrown.
791         $this->expectException('required_capability_exception');
792         core_message_external::confirm_contact_request($user1->id, $user2->id);
793     }
795     /**
796      * Test declining a contact request.
797      */
798     public function test_decline_contact_request() {
799         global $DB;
801         $this->resetAfterTest();
803         $user1 = self::getDataGenerator()->create_user();
804         $user2 = self::getDataGenerator()->create_user();
806         $this->setUser($user1);
808         \core_message\api::create_contact_request($user1->id, $user2->id);
810         $this->setUser($user2);
812         $return = core_message_external::decline_contact_request($user1->id, $user2->id);
813         $return = external_api::clean_returnvalue(core_message_external::decline_contact_request_returns(), $return);
814         $this->assertEquals(array(), $return);
816         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
817         $this->assertEquals(0, $DB->count_records('message_contacts'));
818     }
820     /**
821      * Test declining a contact request with messaging disabled.
822      */
823     public function test_decline_contact_request_messaging_disabled() {
824         global $CFG;
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();
832         $this->setUser($user1);
834         // Disable messaging.
835         $CFG->messaging = 0;
837         // Ensure an exception is thrown.
838         $this->expectException('moodle_exception');
839         core_message_external::decline_contact_request($user1->id, $user2->id);
840     }
842     /**
843      * Test declining a contact request with no permission.
844      */
845     public function test_decline_contact_request_no_permission() {
846         $this->resetAfterTest();
848         // Create some skeleton data just so we can call the WS.
849         $user1 = self::getDataGenerator()->create_user();
850         $user2 = self::getDataGenerator()->create_user();
851         $user3 = self::getDataGenerator()->create_user();
853         $this->setUser($user3);
855         // Ensure an exception is thrown.
856         $this->expectException('required_capability_exception');
857         core_message_external::decline_contact_request($user1->id, $user2->id);
858     }
860     /**
861      * Test blocking a user.
862      */
863     public function test_block_user() {
864         global $DB;
866         $this->resetAfterTest(true);
868         $user1 = self::getDataGenerator()->create_user();
869         $user2 = self::getDataGenerator()->create_user();
871         $this->setUser($user1);
873         // Blocking a user.
874         $return = core_message_external::block_user($user1->id, $user2->id);
875         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
876         $this->assertEquals(array(), $return);
878         // Get list of blocked users.
879         $record = $DB->get_record('message_users_blocked', []);
881         $this->assertEquals($user1->id, $record->userid);
882         $this->assertEquals($user2->id, $record->blockeduserid);
884         // Blocking a user who is already blocked.
885         $return = core_message_external::block_user($user1->id, $user2->id);
886         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
887         $this->assertEquals(array(), $return);
889         $this->assertEquals(1, $DB->count_records('message_users_blocked'));
890     }
892     /**
893      * Test blocking a user with messaging disabled.
894      */
895     public function test_block_user_messaging_disabled() {
896         global $CFG;
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();
904         $this->setUser($user1);
906         // Disable messaging.
907         $CFG->messaging = 0;
909         // Ensure an exception is thrown.
910         $this->expectException('moodle_exception');
911         core_message_external::block_user($user1->id, $user2->id);
912     }
914     /**
915      * Test blocking a user with no permission.
916      */
917     public function test_block_user_no_permission() {
918         $this->resetAfterTest();
920         // Create some skeleton data just so we can call the WS.
921         $user1 = self::getDataGenerator()->create_user();
922         $user2 = self::getDataGenerator()->create_user();
923         $user3 = self::getDataGenerator()->create_user();
925         $this->setUser($user3);
927         // Ensure an exception is thrown.
928         $this->expectException('required_capability_exception');
929         core_message_external::block_user($user1->id, $user2->id);
930     }
932     /**
933      * Test unblocking a user.
934      */
935     public function test_unblock_user() {
936         global $DB;
938         $this->resetAfterTest(true);
940         $user1 = self::getDataGenerator()->create_user();
941         $user2 = self::getDataGenerator()->create_user();
943         $this->setUser($user1);
945         // Block the user.
946         \core_message\api::block_user($user1->id, $user2->id);
948         // Unblocking a user.
949         $return = core_message_external::unblock_user($user1->id, $user2->id);
950         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
951         $this->assertEquals(array(), $return);
953         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
955         // Unblocking a user who is already unblocked.
956         $return = core_message_external::unblock_user($user1->id, $user2->id);
957         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
958         $this->assertEquals(array(), $return);
960         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
961     }
963     /**
964      * Test unblocking a user with messaging disabled.
965      */
966     public function test_unblock_user_messaging_disabled() {
967         global $CFG;
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();
975         $this->setUser($user1);
977         // Disable messaging.
978         $CFG->messaging = 0;
980         // Ensure an exception is thrown.
981         $this->expectException('moodle_exception');
982         core_message_external::unblock_user($user1->id, $user2->id);
983     }
985     /**
986      * Test unblocking a user with no permission.
987      */
988     public function test_unblock_user_no_permission() {
989         $this->resetAfterTest();
991         // Create some skeleton data just so we can call the WS.
992         $user1 = self::getDataGenerator()->create_user();
993         $user2 = self::getDataGenerator()->create_user();
994         $user3 = self::getDataGenerator()->create_user();
996         $this->setUser($user3);
998         // Ensure an exception is thrown.
999         $this->expectException('required_capability_exception');
1000         core_message_external::unblock_user($user1->id, $user2->id);
1001     }
1003     /**
1004      * Test get_contacts.
1005      */
1006     public function test_get_contacts() {
1007         $this->resetAfterTest(true);
1009         $user1 = self::getDataGenerator()->create_user();
1010         $user_stranger = self::getDataGenerator()->create_user();
1011         $user_offline1 = self::getDataGenerator()->create_user();
1012         $user_offline2 = self::getDataGenerator()->create_user();
1013         $user_offline3 = self::getDataGenerator()->create_user();
1014         $user_online = new stdClass();
1015         $user_online->lastaccess = time();
1016         $user_online = self::getDataGenerator()->create_user($user_online);
1017         $user_blocked = self::getDataGenerator()->create_user();
1018         $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
1020         // Login as user1.
1021         $this->setUser($user1);
1022         \core_message\api::add_contact($user1->id, $user_offline1->id);
1023         \core_message\api::add_contact($user1->id, $user_offline2->id);
1024         \core_message\api::add_contact($user1->id, $user_offline3->id);
1025         \core_message\api::add_contact($user1->id, $user_online->id);
1027         // User_stranger sends a couple of messages to user1.
1028         $this->send_message($user_stranger, $user1, 'Hello there!');
1029         $this->send_message($user_stranger, $user1, 'How you goin?');
1030         $this->send_message($user_stranger, $user1, 'Cya!');
1031         $this->send_message($noreplyuser, $user1, 'I am not a real user');
1033         // User_blocked sends a message to user1.
1034         $this->send_message($user_blocked, $user1, 'Here, have some spam.');
1036         // Retrieve the contacts of the user.
1037         $this->setUser($user1);
1038         $contacts = core_message_external::get_contacts();
1039         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1040         $this->assertCount(3, $contacts['offline']);
1041         $this->assertCount(1, $contacts['online']);
1042         $this->assertCount(3, $contacts['strangers']);
1043         core_message_external::block_contacts(array($user_blocked->id));
1044         $this->assertDebuggingCalled();
1045         $contacts = core_message_external::get_contacts();
1046         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1047         $this->assertCount(3, $contacts['offline']);
1048         $this->assertCount(1, $contacts['online']);
1049         $this->assertCount(2, $contacts['strangers']);
1051         // Checking some of the fields returned.
1052         $stranger = array_pop($contacts['strangers']);
1054         $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
1055         $this->assertEquals(1, $stranger['unread']);
1057         // Check that deleted users are not returned.
1058         delete_user($user_offline1);
1059         delete_user($user_stranger);
1060         delete_user($user_online);
1061         $contacts = core_message_external::get_contacts();
1062         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1063         $this->assertCount(2, $contacts['offline']);
1064         $this->assertCount(0, $contacts['online']);
1065         $this->assertCount(1, $contacts['strangers']);
1066     }
1068     /**
1069      * Test search_contacts.
1070      * @expectedException moodle_exception
1071      */
1072     public function test_search_contacts() {
1073         global $DB;
1074         $this->resetAfterTest(true);
1076         $course1 = $this->getDataGenerator()->create_course();
1077         $course2 = $this->getDataGenerator()->create_course();
1079         $user1 = new stdClass();
1080         $user1->firstname = 'X';
1081         $user1->lastname = 'X';
1082         $user1 = $this->getDataGenerator()->create_user($user1);
1083         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1084         $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
1086         $user2 = new stdClass();
1087         $user2->firstname = 'Eric';
1088         $user2->lastname = 'Cartman';
1089         $user2 = self::getDataGenerator()->create_user($user2);
1090         $user3 = new stdClass();
1091         $user3->firstname = 'Stan';
1092         $user3->lastname = 'Marsh';
1093         $user3 = self::getDataGenerator()->create_user($user3);
1094         self::getDataGenerator()->enrol_user($user3->id, $course1->id);
1095         $user4 = new stdClass();
1096         $user4->firstname = 'Kyle';
1097         $user4->lastname = 'Broflovski';
1098         $user4 = self::getDataGenerator()->create_user($user4);
1099         $user5 = new stdClass();
1100         $user5->firstname = 'Kenny';
1101         $user5->lastname = 'McCormick';
1102         $user5 = self::getDataGenerator()->create_user($user5);
1103         self::getDataGenerator()->enrol_user($user5->id, $course2->id);
1105         $this->setUser($user1);
1107         $results = core_message_external::search_contacts('r');
1108         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1109         $this->assertCount(5, $results); // Users 2 through 5 + admin
1111         $results = core_message_external::search_contacts('r', true);
1112         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1113         $this->assertCount(2, $results);
1115         $results = core_message_external::search_contacts('Kyle', false);
1116         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1117         $this->assertCount(1, $results);
1118         $result = reset($results);
1119         $this->assertEquals($user4->id, $result['id']);
1121         $results = core_message_external::search_contacts('y', false);
1122         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1123         $this->assertCount(2, $results);
1125         $results = core_message_external::search_contacts('y', true);
1126         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1127         $this->assertCount(1, $results);
1128         $result = reset($results);
1129         $this->assertEquals($user5->id, $result['id']);
1131         // Empty query, will throw an exception.
1132         $results = core_message_external::search_contacts('');
1133     }
1135     /**
1136      * Test get_messages.
1137      */
1138     public function test_get_messages() {
1139         global $CFG, $DB;
1140         $this->resetAfterTest(true);
1142         $this->preventResetByRollback();
1143         // This mark the messages as read!.
1144         $sink = $this->redirectMessages();
1146         $user1 = self::getDataGenerator()->create_user();
1147         $user2 = self::getDataGenerator()->create_user();
1148         $user3 = self::getDataGenerator()->create_user();
1150         $course = self::getDataGenerator()->create_course();
1152         // Send a message from one user to another.
1153         message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1154         message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
1155         message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1156         message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1157         message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);
1159         $this->setUser($user1);
1160         // Get read conversations from user1 to user2.
1161         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1162         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1163         $this->assertCount(1, $messages['messages']);
1165         // Delete the message.
1166         $message = array_shift($messages['messages']);
1167         \core_message\api::delete_message($user1->id, $message['id']);
1169         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1170         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1171         $this->assertCount(0, $messages['messages']);
1173         // Get unread conversations from user1 to user2.
1174         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
1175         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1176         $this->assertCount(0, $messages['messages']);
1178         // Get read messages send from user1.
1179         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1180         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1181         $this->assertCount(1, $messages['messages']);
1183         $this->setUser($user2);
1184         // Get read conversations from any user to user2.
1185         $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
1186         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1187         $this->assertCount(2, $messages['messages']);
1189         // Conversations from user3 to user2.
1190         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1191         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1192         $this->assertCount(1, $messages['messages']);
1194         // Delete the message.
1195         $message = array_shift($messages['messages']);
1196         \core_message\api::delete_message($user2->id, $message['id']);
1198         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1199         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1200         $this->assertCount(0, $messages['messages']);
1202         $this->setUser($user3);
1203         // Get read notifications received by user3.
1204         $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
1205         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1206         $this->assertCount(0, $messages['messages']);
1208         // Now, create some notifications...
1209         // We are creating fake notifications but based on real ones.
1211         // This one comes from a disabled plugin's provider and therefore is not sent.
1212         $eventdata = new \core\message\message();
1213         $eventdata->courseid          = $course->id;
1214         $eventdata->notification      = 1;
1215         $eventdata->modulename        = 'moodle';
1216         $eventdata->component         = 'enrol_paypal';
1217         $eventdata->name              = 'paypal_enrolment';
1218         $eventdata->userfrom          = get_admin();
1219         $eventdata->userto            = $user1;
1220         $eventdata->subject           = "Moodle: PayPal payment";
1221         $eventdata->fullmessage       = "Your PayPal payment is pending.";
1222         $eventdata->fullmessageformat = FORMAT_PLAIN;
1223         $eventdata->fullmessagehtml   = '';
1224         $eventdata->smallmessage      = '';
1225         message_send($eventdata);
1226         $this->assertDebuggingCalled('Attempt to send msg from a provider enrol_paypal/paypal_enrolment '.
1227             'that is inactive or not allowed for the user id='.$user1->id);
1229         // This one omits notification = 1.
1230         $message = new \core\message\message();
1231         $message->courseid          = $course->id;
1232         $message->component         = 'enrol_manual';
1233         $message->name              = 'expiry_notification';
1234         $message->userfrom          = $user2;
1235         $message->userto            = $user1;
1236         $message->subject           = 'Test: This is not a notification but otherwise is valid';
1237         $message->fullmessage       = 'Test: Full message';
1238         $message->fullmessageformat = FORMAT_MARKDOWN;
1239         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
1240         $message->smallmessage      = $message->subject;
1241         $message->contexturlname    = $course->fullname;
1242         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1243         message_send($message);
1245         $message = new \core\message\message();
1246         $message->courseid          = $course->id;
1247         $message->notification      = 1;
1248         $message->component         = 'enrol_manual';
1249         $message->name              = 'expiry_notification';
1250         $message->userfrom          = $user2;
1251         $message->userto            = $user1;
1252         $message->subject           = 'Enrolment expired';
1253         $message->fullmessage       = 'Enrolment expired blah blah blah';
1254         $message->fullmessageformat = FORMAT_MARKDOWN;
1255         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
1256         $message->smallmessage      = $message->subject;
1257         $message->contexturlname    = $course->fullname;
1258         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1259         message_send($message);
1261         $userfrom = core_user::get_noreply_user();
1262         $userfrom->maildisplay = true;
1263         $eventdata = new \core\message\message();
1264         $eventdata->courseid          = $course->id;
1265         $eventdata->component         = 'moodle';
1266         $eventdata->name              = 'badgecreatornotice';
1267         $eventdata->userfrom          = $userfrom;
1268         $eventdata->userto            = $user1;
1269         $eventdata->notification      = 1;
1270         $eventdata->subject           = 'New badge';
1271         $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
1272         $eventdata->fullmessageformat = FORMAT_PLAIN;
1273         $eventdata->fullmessagehtml   = $eventdata->subject;
1274         $eventdata->smallmessage      = $eventdata->subject;
1275         message_send($eventdata);
1277         $eventdata = new \core\message\message();
1278         $eventdata->courseid         = $course->id;
1279         $eventdata->name             = 'submission';
1280         $eventdata->component        = 'mod_feedback';
1281         $eventdata->userfrom         = $user1;
1282         $eventdata->userto           = $user2;
1283         $eventdata->subject          = 'Feedback submitted';
1284         $eventdata->fullmessage      = 'Feedback submitted from an user';
1285         $eventdata->fullmessageformat = FORMAT_PLAIN;
1286         $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
1287         $eventdata->smallmessage     = '';
1288         message_send($eventdata);
1290         $this->setUser($user1);
1291         // Get read notifications from any user to user1.
1292         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
1293         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1294         $this->assertCount(3, $messages['messages']);
1296         // Get one read notifications from any user to user1.
1297         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
1298         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1299         $this->assertCount(1, $messages['messages']);
1301         // Get unread notifications from any user to user1.
1302         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
1303         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1304         $this->assertCount(0, $messages['messages']);
1306         // Get read both type of messages from any user to user1.
1307         $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
1308         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1309         $this->assertCount(4, $messages['messages']);
1311         // Get read notifications from no-reply-user to user1.
1312         $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
1313         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1314         $this->assertCount(1, $messages['messages']);
1316         // Get notifications send by user1 to any user.
1317         $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
1318         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1319         $this->assertCount(1, $messages['messages']);
1321         // Test warnings.
1322         $CFG->messaging = 0;
1324         $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
1325         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1326         $this->assertCount(1, $messages['warnings']);
1328         // Test exceptions.
1330         // Messaging disabled.
1331         try {
1332             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1333             $this->fail('Exception expected due messaging disabled.');
1334         } catch (moodle_exception $e) {
1335             $this->assertEquals('disabled', $e->errorcode);
1336         }
1338         $CFG->messaging = 1;
1340         // Invalid users.
1341         try {
1342             $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
1343             $this->fail('Exception expected due invalid users.');
1344         } catch (moodle_exception $e) {
1345             $this->assertEquals('accessdenied', $e->errorcode);
1346         }
1348         // Invalid user ids.
1349         try {
1350             $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
1351             $this->fail('Exception expected due invalid users.');
1352         } catch (moodle_exception $e) {
1353             $this->assertEquals('invaliduser', $e->errorcode);
1354         }
1356         // Invalid users (permissions).
1357         $this->setUser($user2);
1358         try {
1359             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1360             $this->fail('Exception expected due invalid user.');
1361         } catch (moodle_exception $e) {
1362             $this->assertEquals('accessdenied', $e->errorcode);
1363         }
1365     }
1367     /**
1368      * Test get_messages where we want all messages from a user, sent to any user.
1369      */
1370     public function test_get_messages_useridto_all() {
1371         $this->resetAfterTest(true);
1373         $user1 = self::getDataGenerator()->create_user();
1374         $user2 = self::getDataGenerator()->create_user();
1375         $user3 = self::getDataGenerator()->create_user();
1377         $this->setUser($user1);
1379         // Send a message from user 1 to two other users.
1380         $this->send_message($user1, $user2, 'some random text 1', 0, 1);
1381         $this->send_message($user1, $user3, 'some random text 2', 0, 2);
1383         // Get messages sent from user 1.
1384         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', false, false, 0, 0);
1385         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1387         // Confirm the data is correct.
1388         $messages = $messages['messages'];
1389         $this->assertCount(2, $messages);
1391         $message1 = array_shift($messages);
1392         $message2 = array_shift($messages);
1394         $this->assertEquals($user1->id, $message1['useridfrom']);
1395         $this->assertEquals($user2->id, $message1['useridto']);
1397         $this->assertEquals($user1->id, $message2['useridfrom']);
1398         $this->assertEquals($user3->id, $message2['useridto']);
1399     }
1401     /**
1402      * Test get_messages where we want all messages to a user, sent by any user.
1403      */
1404     public function test_get_messages_useridfrom_all() {
1405         $this->resetAfterTest();
1407         $user1 = self::getDataGenerator()->create_user();
1408         $user2 = self::getDataGenerator()->create_user();
1409         $user3 = self::getDataGenerator()->create_user();
1411         $this->setUser($user1);
1413         // Send a message to user 1 from two other users.
1414         $this->send_message($user2, $user1, 'some random text 1', 0, 1);
1415         $this->send_message($user3, $user1, 'some random text 2', 0, 2);
1417         // Get messages sent to user 1.
1418         $messages = core_message_external::get_messages($user1->id, 0, 'conversations', false, false, 0, 0);
1419         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1421         // Confirm the data is correct.
1422         $messages = $messages['messages'];
1423         $this->assertCount(2, $messages);
1425         $message1 = array_shift($messages);
1426         $message2 = array_shift($messages);
1428         $this->assertEquals($user2->id, $message1['useridfrom']);
1429         $this->assertEquals($user1->id, $message1['useridto']);
1431         $this->assertEquals($user3->id, $message2['useridfrom']);
1432         $this->assertEquals($user1->id, $message2['useridto']);
1433     }
1435     /**
1436      * Test get_blocked_users.
1437      */
1438     public function test_get_blocked_users() {
1439         $this->resetAfterTest(true);
1441         $user1 = self::getDataGenerator()->create_user();
1442         $userstranger = self::getDataGenerator()->create_user();
1443         $useroffline1 = self::getDataGenerator()->create_user();
1444         $useroffline2 = self::getDataGenerator()->create_user();
1445         $userblocked = self::getDataGenerator()->create_user();
1447         // Login as user1.
1448         $this->setUser($user1);
1450         \core_message\api::add_contact($user1->id, $useroffline1->id);
1451         \core_message\api::add_contact($user1->id, $useroffline2->id);
1453         // The userstranger sends a couple of messages to user1.
1454         $this->send_message($userstranger, $user1, 'Hello there!');
1455         $this->send_message($userstranger, $user1, 'How you goin?');
1457         // The userblocked sends a message to user1.
1458         // Note that this user is not blocked at this point.
1459         $this->send_message($userblocked, $user1, 'Here, have some spam.');
1461         // Retrieve the list of blocked users.
1462         $this->setUser($user1);
1463         $blockedusers = core_message_external::get_blocked_users($user1->id);
1464         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1465         $this->assertCount(0, $blockedusers['users']);
1467         // Block the $userblocked and retrieve again the list.
1468         core_message_external::block_contacts(array($userblocked->id));
1469         $this->assertDebuggingCalled();
1470         $blockedusers = core_message_external::get_blocked_users($user1->id);
1471         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1472         $this->assertCount(1, $blockedusers['users']);
1474         // Remove the $userblocked and check that the list now is empty.
1475         delete_user($userblocked);
1476         $blockedusers = core_message_external::get_blocked_users($user1->id);
1477         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1478         $this->assertCount(0, $blockedusers['users']);
1479     }
1481     /**
1482      * Test mark_message_read.
1483      */
1484     public function test_mark_message_read() {
1485         $this->resetAfterTest(true);
1487         $user1 = self::getDataGenerator()->create_user();
1488         $user2 = self::getDataGenerator()->create_user();
1489         $user3 = self::getDataGenerator()->create_user();
1491         // Login as user1.
1492         $this->setUser($user1);
1493         \core_message\api::add_contact($user1->id, $user2->id);
1494         \core_message\api::add_contact($user1->id, $user3->id);
1496         // The user2 sends a couple of messages to user1.
1497         $this->send_message($user2, $user1, 'Hello there!');
1498         $this->send_message($user2, $user1, 'How you goin?');
1499         $this->send_message($user3, $user1, 'How you goin?');
1500         $this->send_message($user3, $user2, 'How you goin?');
1502         // Retrieve all messages sent by user2 (they are currently unread).
1503         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1505         $messageids = array();
1506         foreach ($lastmessages as $m) {
1507             $messageid = core_message_external::mark_message_read($m->id, time());
1508             $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
1509         }
1511         // Retrieve all messages sent (they are currently read).
1512         $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
1513         $this->assertCount(2, $lastmessages);
1514         $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
1515         $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
1517         // Retrieve all messages sent by any user (that are currently unread).
1518         $lastmessages = message_get_messages($user1->id, 0, 0, false);
1519         $this->assertCount(1, $lastmessages);
1521         // Invalid message ids.
1522         try {
1523             $messageid = core_message_external::mark_message_read(1337, time());
1524             $this->fail('Exception expected due invalid messageid.');
1525         } catch (dml_missing_record_exception $e) {
1526             $this->assertEquals('invalidrecordunknown', $e->errorcode);
1527         }
1529         // A message to a different user.
1530         $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
1531         $messageid = array_pop($lastmessages)->id;
1532         try {
1533             $messageid = core_message_external::mark_message_read($messageid, time());
1534             $this->fail('Exception expected due invalid messageid.');
1535         } catch (invalid_parameter_exception $e) {
1536             $this->assertEquals('invalidparameter', $e->errorcode);
1537         }
1538     }
1540     /**
1541      * Test mark_notification_read.
1542      */
1543     public function test_mark_notification_read() {
1544         $this->resetAfterTest(true);
1546         $user1 = self::getDataGenerator()->create_user();
1547         $user2 = self::getDataGenerator()->create_user();
1548         $user3 = self::getDataGenerator()->create_user();
1550         // Login as user1.
1551         $this->setUser($user1);
1552         \core_message\api::add_contact($user1->id, $user2->id);
1553         \core_message\api::add_contact($user1->id, $user3->id);
1555         // The user2 sends a couple of notifications to user1.
1556         $this->send_message($user2, $user1, 'Hello there!', 1);
1557         $this->send_message($user2, $user1, 'How you goin?', 1);
1558         $this->send_message($user3, $user1, 'How you goin?', 1);
1559         $this->send_message($user3, $user2, 'How you goin?', 1);
1561         // Retrieve all notifications sent by user2 (they are currently unread).
1562         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, false);
1564         $notificationids = array();
1565         foreach ($lastnotifications as $n) {
1566             $notificationid = core_message_external::mark_notification_read($n->id, time());
1567             $notificationids[] = external_api::clean_returnvalue(core_message_external::mark_notification_read_returns(),
1568                 $notificationid);
1569         }
1571         // Retrieve all notifications sent (they are currently read).
1572         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, true);
1573         $this->assertCount(2, $lastnotifications);
1574         $this->assertArrayHasKey($notificationids[1]['notificationid'], $lastnotifications);
1575         $this->assertArrayHasKey($notificationids[0]['notificationid'], $lastnotifications);
1577         // Retrieve all notifications sent by any user (that are currently unread).
1578         $lastnotifications = message_get_messages($user1->id, 0, 1, false);
1579         $this->assertCount(1, $lastnotifications);
1581         // Invalid notification ids.
1582         try {
1583             $notificationid = core_message_external::mark_notification_read(1337, time());
1584             $this->fail('Exception expected due invalid notificationid.');
1585         } catch (dml_missing_record_exception $e) {
1586             $this->assertEquals('invalidrecord', $e->errorcode);
1587         }
1589         // A notification to a different user.
1590         $lastnotifications = message_get_messages($user2->id, $user3->id, 1, false);
1591         $notificationid = array_pop($lastnotifications)->id;
1592         try {
1593             $notificationid = core_message_external::mark_notification_read($notificationid, time());
1594             $this->fail('Exception expected due invalid notificationid.');
1595         } catch (invalid_parameter_exception $e) {
1596             $this->assertEquals('invalidparameter', $e->errorcode);
1597         }
1598     }
1600     /**
1601      * Test delete_message.
1602      */
1603     public function test_delete_message() {
1604         global $DB;
1605         $this->resetAfterTest(true);
1607         $user1 = self::getDataGenerator()->create_user();
1608         $user2 = self::getDataGenerator()->create_user();
1609         $user3 = self::getDataGenerator()->create_user();
1610         $user4 = self::getDataGenerator()->create_user();
1612         // Login as user1.
1613         $this->setUser($user1);
1614         \core_message\api::add_contact($user1->id, $user2->id);
1615         \core_message\api::add_contact($user1->id, $user3->id);
1617         // User user1 does not interchange messages with user3.
1618         $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1619         $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1620         $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1621         $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
1623         // Retrieve all messages sent by user2 (they are currently unread).
1624         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1626         // Delete a message not read, as a user from.
1627         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1628         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1629         $this->assertTrue($result['status']);
1630         $this->assertCount(0, $result['warnings']);
1631         $mua = $DB->get_record('message_user_actions', array('messageid' => $m1to2, 'userid' => $user1->id));
1632         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua->action);
1634         // Try to delete the same message again.
1635         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1636         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1637         $this->assertFalse($result['status']);
1639         // Try to delete a message that does not belong to me.
1640         try {
1641             $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
1642             $this->fail('Exception expected due invalid messageid.');
1643         } catch (moodle_exception $e) {
1644             $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
1645         }
1647         $this->setUser($user3);
1648         // Delete a message not read, as a user to.
1649         $result = core_message_external::delete_message($m2to3, $user3->id, false);
1650         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1651         $this->assertTrue($result['status']);
1652         $this->assertCount(0, $result['warnings']);
1653         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m2to3, 'userid' => $user3->id,
1654             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1656         // Delete a message read.
1657         $message = $DB->get_record('messages', ['id' => $m3to2]);
1658         \core_message\api::mark_message_as_read($user3->id, $message, time());
1659         $result = core_message_external::delete_message($m3to2, $user3->id);
1660         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1661         $this->assertTrue($result['status']);
1662         $this->assertCount(0, $result['warnings']);
1663         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to2, 'userid' => $user3->id,
1664             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1666         // Invalid message ids.
1667         try {
1668             $result = core_message_external::delete_message(-1, $user1->id);
1669             $this->fail('Exception expected due invalid messageid.');
1670         } catch (dml_missing_record_exception $e) {
1671             $this->assertEquals('invalidrecord', $e->errorcode);
1672         }
1674         // Invalid user.
1675         try {
1676             $result = core_message_external::delete_message($m1to2, -1, false);
1677             $this->fail('Exception expected due invalid user.');
1678         } catch (moodle_exception $e) {
1679             $this->assertEquals('invaliduser', $e->errorcode);
1680         }
1682         // Not active user.
1683         delete_user($user2);
1684         try {
1685             $result = core_message_external::delete_message($m1to2, $user2->id, false);
1686             $this->fail('Exception expected due invalid user.');
1687         } catch (moodle_exception $e) {
1688             $this->assertEquals('userdeleted', $e->errorcode);
1689         }
1691         // Now, as an admin, try to delete any message.
1692         $this->setAdminUser();
1693         $result = core_message_external::delete_message($m3to4, $user4->id, false);
1694         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1695         $this->assertTrue($result['status']);
1696         $this->assertCount(0, $result['warnings']);
1697         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to4, 'userid' => $user4->id,
1698             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1700     }
1702     public function test_mark_all_notifications_as_read_invalid_user_exception() {
1703         $this->resetAfterTest(true);
1705         $this->expectException('moodle_exception');
1706         core_message_external::mark_all_notifications_as_read(-2132131, 0);
1707     }
1709     public function test_mark_all_notifications_as_read_access_denied_exception() {
1710         $this->resetAfterTest(true);
1712         $sender = $this->getDataGenerator()->create_user();
1713         $user = $this->getDataGenerator()->create_user();
1715         $this->setUser($user);
1716         $this->expectException('moodle_exception');
1717         core_message_external::mark_all_notifications_as_read($sender->id, 0);
1718     }
1720     public function test_mark_all_notifications_as_read_missing_from_user_exception() {
1721         $this->resetAfterTest(true);
1723         $sender = $this->getDataGenerator()->create_user();
1725         $this->setUser($sender);
1726         $this->expectException('moodle_exception');
1727         core_message_external::mark_all_notifications_as_read($sender->id, 99999);
1728     }
1730     public function test_mark_all_notifications_as_read() {
1731         global $DB;
1733         $this->resetAfterTest(true);
1735         $sender1 = $this->getDataGenerator()->create_user();
1736         $sender2 = $this->getDataGenerator()->create_user();
1737         $sender3 = $this->getDataGenerator()->create_user();
1738         $recipient = $this->getDataGenerator()->create_user();
1740         $this->setUser($recipient);
1742         $this->send_message($sender1, $recipient, 'Notification', 1);
1743         $this->send_message($sender1, $recipient, 'Notification', 1);
1744         $this->send_message($sender2, $recipient, 'Notification', 1);
1745         $this->send_message($sender2, $recipient, 'Notification', 1);
1746         $this->send_message($sender3, $recipient, 'Notification', 1);
1747         $this->send_message($sender3, $recipient, 'Notification', 1);
1749         core_message_external::mark_all_notifications_as_read($recipient->id, $sender1->id);
1750         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1751         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1753         $this->assertCount(2, $readnotifications);
1754         $this->assertCount(4, $unreadnotifications);
1756         core_message_external::mark_all_notifications_as_read($recipient->id, 0);
1757         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1758         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1760         $this->assertCount(6, $readnotifications);
1761         $this->assertCount(0, $unreadnotifications);
1762     }
1764     /**
1765      * Test get_user_notification_preferences
1766      */
1767     public function test_get_user_notification_preferences() {
1768         $this->resetAfterTest(true);
1770         $user = self::getDataGenerator()->create_user();
1771         $this->setUser($user);
1773         // Set a couple of preferences to test.
1774         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
1775         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
1777         $prefs = core_message_external::get_user_notification_preferences();
1778         $prefs = external_api::clean_returnvalue(core_message_external::get_user_notification_preferences_returns(), $prefs);
1779         // Check processors.
1780         $this->assertGreaterThanOrEqual(2, count($prefs['preferences']['processors']));
1781         $this->assertEquals($user->id, $prefs['preferences']['userid']);
1783         // Check components.
1784         $this->assertGreaterThanOrEqual(8, count($prefs['preferences']['components']));
1786         // Check some preferences that we previously set.
1787         $found = 0;
1788         foreach ($prefs['preferences']['components'] as $component) {
1789             foreach ($component['notifications'] as $prefdata) {
1790                 if ($prefdata['preferencekey'] != 'message_provider_mod_assign_assign_notification') {
1791                     continue;
1792                 }
1793                 foreach ($prefdata['processors'] as $processor) {
1794                     if ($processor['name'] == 'popup') {
1795                         $this->assertTrue($processor['loggedin']['checked']);
1796                         $found++;
1797                     } else if ($processor['name'] == 'email') {
1798                         $this->assertTrue($processor['loggedoff']['checked']);
1799                         $found++;
1800                     }
1801                 }
1802             }
1803         }
1804         $this->assertEquals(2, $found);
1805     }
1807     /**
1808      * Test get_user_notification_preferences permissions
1809      */
1810     public function test_get_user_notification_preferences_permissions() {
1811         $this->resetAfterTest(true);
1813         $user = self::getDataGenerator()->create_user();
1814         $otheruser = self::getDataGenerator()->create_user();
1815         $this->setUser($user);
1817         $this->expectException('moodle_exception');
1818         $prefs = core_message_external::get_user_notification_preferences($otheruser->id);
1819     }
1821     /**
1822      * Tests searching users in a course.
1823      */
1824     public function test_messagearea_search_users_in_course() {
1825         $this->resetAfterTest(true);
1827         // Create some users.
1828         $user1 = new stdClass();
1829         $user1->firstname = 'User';
1830         $user1->lastname = 'One';
1831         $user1 = self::getDataGenerator()->create_user($user1);
1833         // The person doing the search.
1834         $this->setUser($user1);
1836         // Set the second user's status to online by setting their last access to now.
1837         $user2 = new stdClass();
1838         $user2->firstname = 'User';
1839         $user2->lastname = 'Two';
1840         $user2->lastaccess = time();
1841         $user2 = self::getDataGenerator()->create_user($user2);
1843         // Block the second user.
1844         \core_message\api::block_user($user1->id, $user2->id);
1846         $user3 = new stdClass();
1847         $user3->firstname = 'User';
1848         $user3->lastname = 'Three';
1849         $user3 = self::getDataGenerator()->create_user($user3);
1851         // Create a course.
1852         $course1 = new stdClass();
1853         $course1->fullname = 'Course';
1854         $course1->shortname = 'One';
1855         $course1 = $this->getDataGenerator()->create_course();
1857         // Enrol the user we are doing the search for and one user in the course.
1858         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1859         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1861         // Perform a search.
1862         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1864         // We need to execute the return values cleaning process to simulate the web service.
1865         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1866             $result);
1868         // Check that we only retrieved a user that was enrolled, and that the user performing the search was not returned.
1869         $users = $result['contacts'];
1870         $this->assertCount(1, $users);
1872         $user = $users[0];
1873         $this->assertEquals($user2->id, $user['userid']);
1874         $this->assertEquals(fullname($user2), $user['fullname']);
1875         $this->assertFalse($user['ismessaging']);
1876         $this->assertFalse($user['sentfromcurrentuser']);
1877         $this->assertNull($user['lastmessage']);
1878         $this->assertNull($user['messageid']);
1879         $this->assertNull($user['isonline']);
1880         $this->assertFalse($user['isread']);
1881         $this->assertTrue($user['isblocked']);
1882         $this->assertNull($user['unreadcount']);
1883     }
1885     /**
1886      * Tests searching users in course as another user.
1887      */
1888     public function test_messagearea_search_users_in_course_as_other_user() {
1889         $this->resetAfterTest(true);
1891         // The person doing the search for another user.
1892         $this->setAdminUser();
1894         // Create some users.
1895         $user1 = new stdClass();
1896         $user1->firstname = 'User';
1897         $user1->lastname = 'One';
1898         $user1 = self::getDataGenerator()->create_user($user1);
1900         $user2 = new stdClass();
1901         $user2->firstname = 'User';
1902         $user2->lastname = 'Two';
1903         $user2 = self::getDataGenerator()->create_user($user2);
1905         $user3 = new stdClass();
1906         $user3->firstname = 'User';
1907         $user3->lastname = 'Three';
1908         $user3 = self::getDataGenerator()->create_user($user3);
1910         // Create a course.
1911         $course1 = new stdClass();
1912         $course1->fullname = 'Course';
1913         $course1->shortname = 'One';
1914         $course1 = $this->getDataGenerator()->create_course();
1916         // Enrol the user we are doing the search for and one user in the course.
1917         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1918         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1920         // Perform a search.
1921         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1923         // We need to execute the return values cleaning process to simulate the web service server.
1924         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1925             $result);
1927         // Check that we got the user enrolled, and that the user we are performing the search on behalf of was not returned.
1928         $users = $result['contacts'];
1929         $this->assertCount(1, $users);
1931         $user = $users[0];
1932         $this->assertEquals($user2->id, $user['userid']);
1933         $this->assertEquals(fullname($user2), $user['fullname']);
1934         $this->assertFalse($user['ismessaging']);
1935         $this->assertFalse($user['sentfromcurrentuser']);
1936         $this->assertNull($user['lastmessage']);
1937         $this->assertNull($user['messageid']);
1938         $this->assertFalse($user['isonline']);
1939         $this->assertFalse($user['isread']);
1940         $this->assertFalse($user['isblocked']);
1941         $this->assertNull($user['unreadcount']);
1942     }
1944     /**
1945      * Tests searching users in course as another user without the proper capabilities.
1946      */
1947     public function test_messagearea_search_users_in_course_as_other_user_without_cap() {
1948         $this->resetAfterTest(true);
1950         // Create some users.
1951         $user1 = self::getDataGenerator()->create_user();
1952         $user2 = self::getDataGenerator()->create_user();
1954         // The person doing the search for another user.
1955         $this->setUser($user1);
1957         // Create a course.
1958         $course = $this->getDataGenerator()->create_course();
1960         // Ensure an exception is thrown.
1961         $this->expectException('moodle_exception');
1962         core_message_external::data_for_messagearea_search_users_in_course($user2->id, $course->id, 'User');
1963     }
1965     /**
1966      * Tests searching users in course with messaging disabled.
1967      */
1968     public function test_messagearea_search_users_in_course_messaging_disabled() {
1969         global $CFG;
1971         $this->resetAfterTest(true);
1973         // Create some skeleton data just so we can call the WS..
1974         $user = self::getDataGenerator()->create_user();
1975         $course = $this->getDataGenerator()->create_course();
1977         // The person doing the search for another user.
1978         $this->setUser($user);
1980         // Disable messaging.
1981         $CFG->messaging = 0;
1983         // Ensure an exception is thrown.
1984         $this->expectException('moodle_exception');
1985         core_message_external::data_for_messagearea_search_users_in_course($user->id, $course->id, 'User');
1986     }
1988     /**
1989      * Tests searching users.
1990      */
1991     public function test_messagearea_search_users() {
1992         $this->resetAfterTest(true);
1994         // Create some users.
1995         $user1 = new stdClass();
1996         $user1->firstname = 'User';
1997         $user1->lastname = 'One';
1998         $user1 = self::getDataGenerator()->create_user($user1);
2000         // Set as the user performing the search.
2001         $this->setUser($user1);
2003         $user2 = new stdClass();
2004         $user2->firstname = 'User search';
2005         $user2->lastname = 'Two';
2006         $user2 = self::getDataGenerator()->create_user($user2);
2008         $user3 = new stdClass();
2009         $user3->firstname = 'User search';
2010         $user3->lastname = 'Three';
2011         $user3 = self::getDataGenerator()->create_user($user3);
2013         $user4 = new stdClass();
2014         $user4->firstname = 'User';
2015         $user4->lastname = 'Four';
2016         $user4 = self::getDataGenerator()->create_user($user4);
2018         $user5 = new stdClass();
2019         $user5->firstname = 'User search';
2020         $user5->lastname = 'Five';
2021         $user5 = self::getDataGenerator()->create_user($user5);
2023         $user6 = new stdClass();
2024         $user6->firstname = 'User';
2025         $user6->lastname = 'Six';
2026         $user6 = self::getDataGenerator()->create_user($user6);
2028         // Create some courses.
2029         $course1 = new stdClass();
2030         $course1->fullname = 'Course search';
2031         $course1->shortname = 'One';
2032         $course1 = $this->getDataGenerator()->create_course($course1);
2034         $course2 = new stdClass();
2035         $course2->fullname = 'Course';
2036         $course2->shortname = 'Two';
2037         $course2 = $this->getDataGenerator()->create_course($course2);
2039         $course3 = new stdClass();
2040         $course3->fullname = 'Course';
2041         $course3->shortname = 'Three search';
2042         $course3 = $this->getDataGenerator()->create_course($course3);
2044         $course4 = new stdClass();
2045         $course4->fullname = 'Course Four';
2046         $course4->shortname = 'CF100';
2047         $course4 = $this->getDataGenerator()->create_course($course4);
2049         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
2050         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'student');
2051         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 'student');
2053         // Add some users as contacts.
2054         \core_message\api::add_contact($user1->id, $user2->id);
2055         \core_message\api::add_contact($user1->id, $user3->id);
2056         \core_message\api::add_contact($user1->id, $user4->id);
2058         // Perform a search.
2059         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2061         // We need to execute the return values cleaning process to simulate the web service server.
2062         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2063             $result);
2065         // Confirm that we returns contacts, courses and non-contacts.
2066         $contacts = $result['contacts'];
2067         $courses = $result['courses'];
2068         $noncontacts = $result['noncontacts'];
2070         // Check that we retrieved the correct contacts.
2071         $this->assertCount(2, $contacts);
2072         $this->assertEquals($user3->id, $contacts[0]['userid']);
2073         $this->assertEquals($user2->id, $contacts[1]['userid']);
2075         // Check that we retrieved the correct courses.
2076         $this->assertCount(2, $courses);
2077         $this->assertEquals($course3->id, $courses[0]['id']);
2078         $this->assertEquals($course1->id, $courses[1]['id']);
2080         // Check that we retrieved the correct non-contacts.
2081         $this->assertCount(1, $noncontacts);
2082         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2083     }
2085     /**
2086      * Tests searching users as another user.
2087      */
2088     public function test_messagearea_search_users_as_other_user() {
2089         $this->resetAfterTest(true);
2091         // The person doing the search.
2092         $this->setAdminUser();
2094         // Create some users.
2095         $user1 = new stdClass();
2096         $user1->firstname = 'User';
2097         $user1->lastname = 'One';
2098         $user1 = self::getDataGenerator()->create_user($user1);
2100         $user2 = new stdClass();
2101         $user2->firstname = 'User search';
2102         $user2->lastname = 'Two';
2103         $user2 = self::getDataGenerator()->create_user($user2);
2105         $user3 = new stdClass();
2106         $user3->firstname = 'User search';
2107         $user3->lastname = 'Three';
2108         $user3 = self::getDataGenerator()->create_user($user3);
2110         $user4 = new stdClass();
2111         $user4->firstname = 'User';
2112         $user4->lastname = 'Four';
2113         $user4 = self::getDataGenerator()->create_user($user4);
2115         $user5 = new stdClass();
2116         $user5->firstname = 'User search';
2117         $user5->lastname = 'Five';
2118         $user5 = self::getDataGenerator()->create_user($user5);
2120         $user6 = new stdClass();
2121         $user6->firstname = 'User';
2122         $user6->lastname = 'Six';
2123         $user6 = self::getDataGenerator()->create_user($user6);
2125         // Create some courses.
2126         $course1 = new stdClass();
2127         $course1->fullname = 'Course search';
2128         $course1->shortname = 'One';
2129         $course1 = $this->getDataGenerator()->create_course($course1);
2131         $course2 = new stdClass();
2132         $course2->fullname = 'Course';
2133         $course2->shortname = 'Two';
2134         $course2 = $this->getDataGenerator()->create_course($course2);
2136         $course3 = new stdClass();
2137         $course3->fullname = 'Course';
2138         $course3->shortname = 'Three search';
2139         $course3 = $this->getDataGenerator()->create_course($course3);
2141         // Add some users as contacts.
2142         \core_message\api::add_contact($user1->id, $user2->id);
2143         \core_message\api::add_contact($user1->id, $user3->id);
2144         \core_message\api::add_contact($user1->id, $user4->id);
2146         // Perform a search.
2147         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2149         // We need to execute the return values cleaning process to simulate the web service server.
2150         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2151             $result);
2153         // Confirm that we returns contacts, courses and non-contacts.
2154         $contacts = $result['contacts'];
2155         $courses = $result['courses'];
2156         $noncontacts = $result['noncontacts'];
2158         // Check that we retrieved the correct contacts.
2159         $this->assertCount(2, $contacts);
2160         $this->assertEquals($user3->id, $contacts[0]['userid']);
2161         $this->assertEquals($user2->id, $contacts[1]['userid']);
2163         // Check that we retrieved the correct courses.
2164         $this->assertCount(0, $courses);
2166         // Check that we retrieved the correct non-contacts.
2167         $this->assertCount(1, $noncontacts);
2168         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2169     }
2171     /**
2172      * Tests searching users as another user without the proper capabilities.
2173      */
2174     public function test_messagearea_search_users_as_other_user_without_cap() {
2175         $this->resetAfterTest(true);
2177         // Create some users.
2178         $user1 = self::getDataGenerator()->create_user();
2179         $user2 = self::getDataGenerator()->create_user();
2181         // The person doing the search for another user.
2182         $this->setUser($user1);
2184         // Ensure an exception is thrown.
2185         $this->expectException('moodle_exception');
2186         core_message_external::data_for_messagearea_search_users($user2->id, 'User');
2187     }
2189     /**
2190      * Tests searching users with messaging disabled.
2191      */
2192     public function test_messagearea_search_users_messaging_disabled() {
2193         global $CFG;
2195         $this->resetAfterTest(true);
2197         // Create some skeleton data just so we can call the WS.
2198         $user = self::getDataGenerator()->create_user();
2200         // The person doing the search.
2201         $this->setUser($user);
2203         // Disable messaging.
2204         $CFG->messaging = 0;
2206         // Ensure an exception is thrown.
2207         $this->expectException('moodle_exception');
2208         core_message_external::data_for_messagearea_search_users($user->id, 'User');
2209     }
2211     /**
2212      * Tests searching messages.
2213      */
2214     public function test_messagearea_search_messages() {
2215         $this->resetAfterTest(true);
2217         // Create some users.
2218         $user1 = self::getDataGenerator()->create_user();
2219         $user2 = self::getDataGenerator()->create_user();
2221         // The person doing the search.
2222         $this->setUser($user1);
2224         // Send some messages back and forth.
2225         $time = time();
2226         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2227         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2228         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2229         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2231         // Perform a search.
2232         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2234         // We need to execute the return values cleaning process to simulate the web service server.
2235         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2236             $result);
2238         // Confirm the data is correct.
2239         $messages = $result['contacts'];
2240         $this->assertCount(2, $messages);
2242         $message1 = $messages[0];
2243         $message2 = $messages[1];
2245         $this->assertEquals($user2->id, $message1['userid']);
2246         $this->assertEquals(fullname($user2), $message1['fullname']);
2247         $this->assertTrue($message1['ismessaging']);
2248         $this->assertFalse($message1['sentfromcurrentuser']);
2249         $this->assertEquals('Word.', $message1['lastmessage']);
2250         $this->assertNotEmpty($message1['messageid']);
2251         $this->assertNull($message1['isonline']);
2252         $this->assertFalse($message1['isread']);
2253         $this->assertFalse($message1['isblocked']);
2254         $this->assertNull($message1['unreadcount']);
2256         $this->assertEquals($user2->id, $message2['userid']);
2257         $this->assertEquals(fullname($user2), $message2['fullname']);
2258         $this->assertTrue($message2['ismessaging']);
2259         $this->assertTrue($message2['sentfromcurrentuser']);
2260         $this->assertEquals('Yo!', $message2['lastmessage']);
2261         $this->assertNotEmpty($message2['messageid']);
2262         $this->assertNull($message2['isonline']);
2263         $this->assertTrue($message2['isread']);
2264         $this->assertFalse($message2['isblocked']);
2265         $this->assertNull($message2['unreadcount']);
2266     }
2268     /**
2269      * Tests searching messages as another user.
2270      */
2271     public function test_messagearea_search_messages_as_other_user() {
2272         $this->resetAfterTest(true);
2274         // The person doing the search.
2275         $this->setAdminUser();
2277         // Create some users.
2278         $user1 = self::getDataGenerator()->create_user();
2279         $user2 = self::getDataGenerator()->create_user();
2281         // Send some messages back and forth.
2282         $time = time();
2283         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2284         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2285         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2286         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2288         // Perform a search.
2289         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2291         // We need to execute the return values cleaning process to simulate the web service server.
2292         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2293             $result);
2295         // Confirm the data is correct.
2296         $messages = $result['contacts'];
2297         $this->assertCount(2, $messages);
2299         $message1 = $messages[0];
2300         $message2 = $messages[1];
2302         $this->assertEquals($user2->id, $message1['userid']);
2303         $this->assertEquals(fullname($user2), $message1['fullname']);
2304         $this->assertTrue($message1['ismessaging']);
2305         $this->assertFalse($message1['sentfromcurrentuser']);
2306         $this->assertEquals('Word.', $message1['lastmessage']);
2307         $this->assertNotEmpty($message1['messageid']);
2308         $this->assertFalse($message1['isonline']);
2309         $this->assertFalse($message1['isread']);
2310         $this->assertFalse($message1['isblocked']);
2311         $this->assertNull($message1['unreadcount']);
2313         $this->assertEquals($user2->id, $message2['userid']);
2314         $this->assertEquals(fullname($user2), $message2['fullname']);
2315         $this->assertTrue($message2['ismessaging']);
2316         $this->assertTrue($message2['sentfromcurrentuser']);
2317         $this->assertEquals('Yo!', $message2['lastmessage']);
2318         $this->assertNotEmpty($message2['messageid']);
2319         $this->assertFalse($message2['isonline']);
2320         $this->assertTrue($message2['isread']);
2321         $this->assertFalse($message2['isblocked']);
2322         $this->assertNull($message2['unreadcount']);
2323     }
2325     /**
2326      * Tests searching messages as another user without the proper capabilities.
2327      */
2328     public function test_messagearea_search_messages_as_other_user_without_cap() {
2329         $this->resetAfterTest(true);
2331         // Create some users.
2332         $user1 = self::getDataGenerator()->create_user();
2333         $user2 = self::getDataGenerator()->create_user();
2335         // The person doing the search for another user.
2336         $this->setUser($user1);
2338         // Ensure an exception is thrown.
2339         $this->expectException('moodle_exception');
2340         core_message_external::data_for_messagearea_search_messages($user2->id, 'Search');
2341     }
2343     /**
2344      * Tests searching messages with messaging disabled
2345      */
2346     public function test_messagearea_search_messages_messaging_disabled() {
2347         global $CFG;
2349         $this->resetAfterTest(true);
2351         // Create some skeleton data just so we can call the WS.
2352         $user = self::getDataGenerator()->create_user();
2354         // The person doing the search .
2355         $this->setUser($user);
2357         // Disable messaging.
2358         $CFG->messaging = 0;
2360         // Ensure an exception is thrown.
2361         $this->expectException('moodle_exception');
2362         core_message_external::data_for_messagearea_search_messages($user->id, 'Search');
2363     }
2365     /**
2366      * Tests retrieving conversations.
2367      */
2368     public function test_messagearea_conversations() {
2369         $this->resetAfterTest(true);
2371         // Create some users.
2372         $user1 = self::getDataGenerator()->create_user();
2373         $user2 = self::getDataGenerator()->create_user();
2374         $user3 = self::getDataGenerator()->create_user();
2375         $user4 = self::getDataGenerator()->create_user();
2377         // The person retrieving the conversations.
2378         $this->setUser($user1);
2380         // Send some messages back and forth, have some different conversations with different users.
2381         $time = time();
2382         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2383         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2384         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2385         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2387         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2388         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2389         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2390         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2392         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2393         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2394         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2396         // Retrieve the conversations.
2397         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2399         // We need to execute the return values cleaning process to simulate the web service server.
2400         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2401             $result);
2403         // Confirm the data is correct.
2404         $messages = $result['contacts'];
2405         $this->assertCount(3, $messages);
2407         $message1 = $messages[0];
2408         $message2 = $messages[1];
2409         $message3 = $messages[2];
2411         $this->assertEquals($user4->id, $message1['userid']);
2412         $this->assertTrue($message1['ismessaging']);
2413         $this->assertTrue($message1['sentfromcurrentuser']);
2414         $this->assertEquals('Dope.', $message1['lastmessage']);
2415         $this->assertEquals($messageid3, $message1['messageid']);
2416         $this->assertNull($message1['isonline']);
2417         $this->assertFalse($message1['isread']);
2418         $this->assertFalse($message1['isblocked']);
2419         $this->assertEquals(1, $message1['unreadcount']);
2421         $this->assertEquals($user3->id, $message2['userid']);
2422         $this->assertTrue($message2['ismessaging']);
2423         $this->assertFalse($message2['sentfromcurrentuser']);
2424         $this->assertEquals('Cool.', $message2['lastmessage']);
2425         $this->assertEquals($messageid2, $message2['messageid']);
2426         $this->assertNull($message2['isonline']);
2427         $this->assertFalse($message2['isread']);
2428         $this->assertFalse($message2['isblocked']);
2429         $this->assertEquals(2, $message2['unreadcount']);
2431         $this->assertEquals($user2->id, $message3['userid']);
2432         $this->assertTrue($message3['ismessaging']);
2433         $this->assertFalse($message3['sentfromcurrentuser']);
2434         $this->assertEquals('Word.', $message3['lastmessage']);
2435         $this->assertEquals($messageid1, $message3['messageid']);
2436         $this->assertNull($message3['isonline']);
2437         $this->assertFalse($message3['isread']);
2438         $this->assertFalse($message3['isblocked']);
2439         $this->assertEquals(2, $message3['unreadcount']);
2440     }
2442     /**
2443      * Tests retrieving conversations as another user.
2444      */
2445     public function test_messagearea_conversations_as_other_user() {
2446         $this->resetAfterTest(true);
2448         // Set as admin.
2449         $this->setAdminUser();
2451         // Create some users.
2452         $user1 = self::getDataGenerator()->create_user();
2453         $user2 = self::getDataGenerator()->create_user();
2454         $user3 = self::getDataGenerator()->create_user();
2455         $user4 = self::getDataGenerator()->create_user();
2457         // Send some messages back and forth, have some different conversations with different users.
2458         $time = time();
2459         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2460         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2461         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2462         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2464         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2465         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2466         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2467         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2469         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2470         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2471         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2473         // Retrieve the conversations.
2474         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2476         // We need to execute the return values cleaning process to simulate the web service server.
2477         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2478             $result);
2480         // Confirm the data is correct.
2481         $messages = $result['contacts'];
2482         $this->assertCount(3, $messages);
2484         $message1 = $messages[0];
2485         $message2 = $messages[1];
2486         $message3 = $messages[2];
2488         $this->assertEquals($user4->id, $message1['userid']);
2489         $this->assertTrue($message1['ismessaging']);
2490         $this->assertTrue($message1['sentfromcurrentuser']);
2491         $this->assertEquals('Dope.', $message1['lastmessage']);
2492         $this->assertEquals($messageid3, $message1['messageid']);
2493         $this->assertFalse($message1['isonline']);
2494         $this->assertFalse($message1['isread']);
2495         $this->assertFalse($message1['isblocked']);
2496         $this->assertEquals(1, $message1['unreadcount']);
2498         $this->assertEquals($user3->id, $message2['userid']);
2499         $this->assertTrue($message2['ismessaging']);
2500         $this->assertFalse($message2['sentfromcurrentuser']);
2501         $this->assertEquals('Cool.', $message2['lastmessage']);
2502         $this->assertEquals($messageid2, $message2['messageid']);
2503         $this->assertFalse($message2['isonline']);
2504         $this->assertFalse($message2['isread']);
2505         $this->assertFalse($message2['isblocked']);
2506         $this->assertEquals(2, $message2['unreadcount']);
2508         $this->assertEquals($user2->id, $message3['userid']);
2509         $this->assertTrue($message3['ismessaging']);
2510         $this->assertFalse($message3['sentfromcurrentuser']);
2511         $this->assertEquals('Word.', $message3['lastmessage']);
2512         $this->assertEquals($messageid1, $message3['messageid']);
2513         $this->assertFalse($message3['isonline']);
2514         $this->assertFalse($message3['isread']);
2515         $this->assertFalse($message3['isblocked']);
2516         $this->assertEquals(2, $message3['unreadcount']);
2517     }
2519     /**
2520      * Tests retrieving conversations as another user without the proper capabilities.
2521      */
2522     public function test_messagearea_conversations_as_other_user_without_cap() {
2523         $this->resetAfterTest(true);
2525         // Create some users.
2526         $user1 = self::getDataGenerator()->create_user();
2527         $user2 = self::getDataGenerator()->create_user();
2529         // The person retrieving the conversations for another user.
2530         $this->setUser($user1);
2532         // Ensure an exception is thrown.
2533         $this->expectException('moodle_exception');
2534         core_message_external::data_for_messagearea_conversations($user2->id);
2535     }
2537     /**
2538      * Tests retrieving conversations with messaging disabled.
2539      */
2540     public function test_messagearea_conversations_messaging_disabled() {
2541         global $CFG;
2543         $this->resetAfterTest(true);
2545         // Create some skeleton data just so we can call the WS.
2546         $user = self::getDataGenerator()->create_user();
2548         // The person retrieving the conversations.
2549         $this->setUser($user);
2551         // Disable messaging.
2552         $CFG->messaging = 0;
2554         // Ensure an exception is thrown.
2555         $this->expectException('moodle_exception');
2556         core_message_external::data_for_messagearea_conversations($user->id);
2557     }
2559     /**
2560      * Tests retrieving contacts.
2561      */
2562     public function test_messagearea_contacts() {
2563         $this->resetAfterTest(true);
2565         // Create some users.
2566         $user1 = self::getDataGenerator()->create_user();
2568         // Set as the user.
2569         $this->setUser($user1);
2571         $user2 = new stdClass();
2572         $user2->firstname = 'User';
2573         $user2->lastname = 'A';
2574         $user2 = self::getDataGenerator()->create_user($user2);
2576         $user3 = new stdClass();
2577         $user3->firstname = 'User';
2578         $user3->lastname = 'B';
2579         $user3 = self::getDataGenerator()->create_user($user3);
2581         $user4 = new stdClass();
2582         $user4->firstname = 'User';
2583         $user4->lastname = 'C';
2584         $user4 = self::getDataGenerator()->create_user($user4);
2586         $user5 = new stdClass();
2587         $user5->firstname = 'User';
2588         $user5->lastname = 'D';
2589         $user5 = self::getDataGenerator()->create_user($user5);
2591         // Add some users as contacts.
2592         \core_message\api::add_contact($user1->id, $user2->id);
2593         \core_message\api::add_contact($user1->id, $user3->id);
2594         \core_message\api::add_contact($user1->id, $user4->id);
2596         // Retrieve the contacts.
2597         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2599         // We need to execute the return values cleaning process to simulate the web service server.
2600         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2601             $result);
2603         // Confirm the data is correct.
2604         $contacts = $result['contacts'];
2605         usort($contacts, ['static', 'sort_contacts']);
2606         $this->assertCount(3, $contacts);
2608         $contact1 = $contacts[0];
2609         $contact2 = $contacts[1];
2610         $contact3 = $contacts[2];
2612         $this->assertEquals($user2->id, $contact1['userid']);
2613         $this->assertFalse($contact1['ismessaging']);
2614         $this->assertFalse($contact1['sentfromcurrentuser']);
2615         $this->assertNull($contact1['lastmessage']);
2616         $this->assertNull($contact1['messageid']);
2617         $this->assertNull($contact1['isonline']);
2618         $this->assertFalse($contact1['isread']);
2619         $this->assertFalse($contact1['isblocked']);
2620         $this->assertNull($contact1['unreadcount']);
2622         $this->assertEquals($user3->id, $contact2['userid']);
2623         $this->assertFalse($contact2['ismessaging']);
2624         $this->assertFalse($contact2['sentfromcurrentuser']);
2625         $this->assertNull($contact2['lastmessage']);
2626         $this->assertNull($contact2['messageid']);
2627         $this->assertNull($contact2['isonline']);
2628         $this->assertFalse($contact2['isread']);
2629         $this->assertFalse($contact2['isblocked']);
2630         $this->assertNull($contact2['unreadcount']);
2632         $this->assertEquals($user4->id, $contact3['userid']);
2633         $this->assertFalse($contact3['ismessaging']);
2634         $this->assertFalse($contact3['sentfromcurrentuser']);
2635         $this->assertNull($contact3['lastmessage']);
2636         $this->assertNull($contact3['messageid']);
2637         $this->assertNull($contact3['isonline']);
2638         $this->assertFalse($contact3['isread']);
2639         $this->assertFalse($contact3['isblocked']);
2640         $this->assertNull($contact3['unreadcount']);
2641     }
2643     /**
2644      * Tests retrieving contacts as another user.
2645      */
2646     public function test_messagearea_contacts_as_other_user() {
2647         $this->resetAfterTest(true);
2649         $this->setAdminUser();
2651         // Create some users.
2652         $user1 = self::getDataGenerator()->create_user();
2654         $user2 = new stdClass();
2655         $user2->firstname = 'User';
2656         $user2->lastname = 'A';
2657         $user2 = self::getDataGenerator()->create_user($user2);
2659         $user3 = new stdClass();
2660         $user3->firstname = 'User';
2661         $user3->lastname = 'B';
2662         $user3 = self::getDataGenerator()->create_user($user3);
2664         $user4 = new stdClass();
2665         $user4->firstname = 'User';
2666         $user4->lastname = 'C';
2667         $user4 = self::getDataGenerator()->create_user($user4);
2669         $user5 = new stdClass();
2670         $user5->firstname = 'User';
2671         $user5->lastname = 'D';
2672         $user5 = self::getDataGenerator()->create_user($user5);
2674         // Add some users as contacts.
2675         \core_message\api::add_contact($user1->id, $user2->id);
2676         \core_message\api::add_contact($user1->id, $user3->id);
2677         \core_message\api::add_contact($user1->id, $user4->id);
2679         // Retrieve the contacts.
2680         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2682         // We need to execute the return values cleaning process to simulate the web service server.
2683         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2684             $result);
2686         // Confirm the data is correct.
2687         $contacts = $result['contacts'];
2688         usort($contacts, ['static', 'sort_contacts']);
2689         $this->assertCount(3, $contacts);
2691         $contact1 = $contacts[0];
2692         $contact2 = $contacts[1];
2693         $contact3 = $contacts[2];
2695         $this->assertEquals($user2->id, $contact1['userid']);
2696         $this->assertFalse($contact1['ismessaging']);
2697         $this->assertFalse($contact1['sentfromcurrentuser']);
2698         $this->assertNull($contact1['lastmessage']);
2699         $this->assertNull($contact1['messageid']);
2700         $this->assertFalse($contact1['isonline']);
2701         $this->assertFalse($contact1['isread']);
2702         $this->assertFalse($contact1['isblocked']);
2703         $this->assertNull($contact1['unreadcount']);
2705         $this->assertEquals($user3->id, $contact2['userid']);
2706         $this->assertFalse($contact2['ismessaging']);
2707         $this->assertFalse($contact2['sentfromcurrentuser']);
2708         $this->assertNull($contact2['lastmessage']);
2709         $this->assertNull($contact2['messageid']);
2710         $this->assertFalse($contact2['isonline']);
2711         $this->assertFalse($contact2['isread']);
2712         $this->assertFalse($contact2['isblocked']);
2713         $this->assertNull($contact2['unreadcount']);
2715         $this->assertEquals($user4->id, $contact3['userid']);
2716         $this->assertFalse($contact3['ismessaging']);
2717         $this->assertFalse($contact3['sentfromcurrentuser']);
2718         $this->assertNull($contact3['lastmessage']);
2719         $this->assertNull($contact3['messageid']);
2720         $this->assertFalse($contact3['isonline']);
2721         $this->assertFalse($contact3['isread']);
2722         $this->assertFalse($contact3['isblocked']);
2723         $this->assertNull($contact3['unreadcount']);
2724     }
2726     /**
2727      * Tests retrieving contacts as another user without the proper capabilities.
2728      */
2729     public function test_messagearea_contacts_as_other_user_without_cap() {
2730         $this->resetAfterTest(true);
2732         // Create some users.
2733         $user1 = self::getDataGenerator()->create_user();
2734         $user2 = self::getDataGenerator()->create_user();
2736         // The person retrieving the contacts for another user.
2737         $this->setUser($user1);
2739         // Perform the WS call and ensure an exception is thrown.
2740         $this->expectException('moodle_exception');
2741         core_message_external::data_for_messagearea_contacts($user2->id);
2742     }
2744     /**
2745      * Tests retrieving contacts with messaging disabled.
2746      */
2747     public function test_messagearea_contacts_messaging_disabled() {
2748         global $CFG;
2750         $this->resetAfterTest(true);
2752         // Create some skeleton data just so we can call the WS.
2753         $user = self::getDataGenerator()->create_user();
2755         // The person retrieving the contacts.
2756         $this->setUser($user);
2758         // Disable messaging.
2759         $CFG->messaging = 0;
2761         // Perform the WS call and ensure we are shown that it is disabled.
2762         $this->expectException('moodle_exception');
2763         core_message_external::data_for_messagearea_contacts($user->id);
2764     }
2766     /**
2767      * Tests retrieving messages.
2768      */
2769     public function test_messagearea_messages() {
2770         $this->resetAfterTest(true);
2772         // Create some users.
2773         $user1 = self::getDataGenerator()->create_user();
2774         $user2 = self::getDataGenerator()->create_user();
2776         // The person asking for the messages.
2777         $this->setUser($user1);
2779         // Send some messages back and forth.
2780         $time = time();
2781         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2782         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2783         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2784         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2786         // Retrieve the messages.
2787         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2788         $this->assertDebuggingCalledCount(3);
2790         // We need to execute the return values cleaning process to simulate the web service server.
2791         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2792             $result);
2794         // Check the results are correct.
2795         $this->assertTrue($result['iscurrentuser']);
2796         $this->assertEquals($user1->id, $result['currentuserid']);
2797         $this->assertEquals($user2->id, $result['otheruserid']);
2798         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2799         $this->assertNull($result['isonline']);
2801         // Confirm the message data is correct.
2802         $messages = $result['messages'];
2803         $this->assertCount(4, $messages);
2805         $message1 = $messages[0];
2806         $message2 = $messages[1];
2807         $message3 = $messages[2];
2808         $message4 = $messages[3];
2810         $this->assertEquals($user1->id, $message1['useridfrom']);
2811         $this->assertEquals($user2->id, $message1['useridto']);
2812         $this->assertTrue($message1['displayblocktime']);
2813         $this->assertContains('Yo!', $message1['text']);
2815         $this->assertEquals($user2->id, $message2['useridfrom']);
2816         $this->assertEquals($user1->id, $message2['useridto']);
2817         $this->assertFalse($message2['displayblocktime']);
2818         $this->assertContains('Sup mang?', $message2['text']);
2820         $this->assertEquals($user1->id, $message3['useridfrom']);
2821         $this->assertEquals($user2->id, $message3['useridto']);
2822         $this->assertFalse($message3['displayblocktime']);
2823         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2825         $this->assertEquals($user2->id, $message4['useridfrom']);
2826         $this->assertEquals($user1->id, $message4['useridto']);
2827         $this->assertFalse($message4['displayblocktime']);
2828         $this->assertContains('Word.', $message4['text']);
2829     }
2831     /**
2832      * Tests retrieving messages.
2833      */
2834     public function test_messagearea_messages_timefrom() {
2835         $this->resetAfterTest(true);
2837         // Create some users.
2838         $user1 = self::getDataGenerator()->create_user();
2839         $user2 = self::getDataGenerator()->create_user();
2841         // The person asking for the messages.
2842         $this->setUser($user1);
2844         // Send some messages back and forth.
2845         $time = time();
2846         $this->send_message($user1, $user2, 'Message 1', 0, $time - 4);
2847         $this->send_message($user2, $user1, 'Message 2', 0, $time - 3);
2848         $this->send_message($user1, $user2, 'Message 3', 0, $time - 2);
2849         $this->send_message($user2, $user1, 'Message 4', 0, $time - 1);
2851         // Retrieve the messages from $time - 3, which should be the 3 most recent messages.
2852         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id, 0, 0, false, $time - 3);
2853         $this->assertDebuggingCalledCount(3);
2855         // We need to execute the return values cleaning process to simulate the web service server.
2856         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2857             $result);
2859         // Confirm the message data is correct. We shouldn't get 'Message 1' back.
2860         $messages = $result['messages'];
2861         $this->assertCount(3, $messages);
2863         $message1 = $messages[0];
2864         $message2 = $messages[1];
2865         $message3 = $messages[2];
2867         $this->assertContains('Message 2', $message1['text']);
2868         $this->assertContains('Message 3', $message2['text']);
2869         $this->assertContains('Message 4', $message3['text']);
2870     }
2872     /**
2873      * Tests retrieving messages as another user.
2874      */
2875     public function test_messagearea_messages_as_other_user() {
2876         $this->resetAfterTest(true);
2878         // Set as admin.
2879         $this->setAdminUser();
2881         // Create some users.
2882         $user1 = self::getDataGenerator()->create_user();
2883         $user2 = self::getDataGenerator()->create_user();
2885         // Send some messages back and forth.
2886         $time = time();
2887         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2888         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2889         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2890         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2892         // Retrieve the messages.
2893         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2894         $this->assertDebuggingCalledCount(3);
2896         // We need to execute the return values cleaning process to simulate the web service server.
2897         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2898             $result);
2900         // Check the results are correct.
2901         $this->assertFalse($result['iscurrentuser']);
2902         $this->assertEquals($user1->id, $result['currentuserid']);
2903         $this->assertEquals($user2->id, $result['otheruserid']);
2904         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2905         $this->assertFalse($result['isonline']);
2907         // Confirm the message data is correct.
2908         $messages = $result['messages'];
2909         $this->assertCount(4, $messages);
2911         $message1 = $messages[0];
2912         $message2 = $messages[1];
2913         $message3 = $messages[2];
2914         $message4 = $messages[3];
2916         $this->assertEquals($user1->id, $message1['useridfrom']);
2917         $this->assertEquals($user2->id, $message1['useridto']);
2918         $this->assertTrue($message1['displayblocktime']);
2919         $this->assertContains('Yo!', $message1['text']);
2921         $this->assertEquals($user2->id, $message2['useridfrom']);
2922         $this->assertEquals($user1->id, $message2['useridto']);
2923         $this->assertFalse($message2['displayblocktime']);
2924         $this->assertContains('Sup mang?', $message2['text']);
2926         $this->assertEquals($user1->id, $message3['useridfrom']);
2927         $this->assertEquals($user2->id, $message3['useridto']);
2928         $this->assertFalse($message3['displayblocktime']);
2929         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2931         $this->assertEquals($user2->id, $message4['useridfrom']);
2932         $this->assertEquals($user1->id, $message4['useridto']);
2933         $this->assertFalse($message4['displayblocktime']);
2934         $this->assertContains('Word.', $message4['text']);
2935     }
2937     /**
2938      * Tests retrieving messages as another user without the proper capabilities.
2939      */
2940     public function test_messagearea_messages_as_other_user_without_cap() {
2941         $this->resetAfterTest(true);
2943         // Create some users.
2944         $user1 = self::getDataGenerator()->create_user();
2945         $user2 = self::getDataGenerator()->create_user();
2946         $user3 = self::getDataGenerator()->create_user();
2948         // The person asking for the messages for another user.
2949         $this->setUser($user1);
2951         // Ensure an exception is thrown.
2952         $this->expectException('moodle_exception');
2953         core_message_external::data_for_messagearea_messages($user2->id, $user3->id);
2954     }
2956     /**
2957      * Tests retrieving messages with messaging disabled.
2958      */
2959     public function test_messagearea_messages_messaging_disabled() {
2960         global $CFG;
2962         $this->resetAfterTest(true);
2964         // Create some skeleton data just so we can call the WS.
2965         $user1 = self::getDataGenerator()->create_user();
2966         $user2 = self::getDataGenerator()->create_user();
2968         // The person asking for the messages for another user.
2969         $this->setUser($user1);
2971         // Disable messaging.
2972         $CFG->messaging = 0;
2974         // Ensure an exception is thrown.
2975         $this->expectException('moodle_exception');
2976         core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2977     }
2979     /**
2980      * Tests get_conversation_messages for retrieving messages.
2981      */
2982     public function test_get_conversation_messages() {
2983         $this->resetAfterTest(true);
2985         // Create some users.
2986         $user1 = self::getDataGenerator()->create_user();
2987         $user2 = self::getDataGenerator()->create_user();
2988         $user3 = self::getDataGenerator()->create_user();
2989         $user4 = self::getDataGenerator()->create_user();
2990         $user5 = self::getDataGenerator()->create_user();
2992         // Create group conversation.
2993         $conversation = \core_message\api::create_conversation(
2994             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2995             [$user1->id, $user2->id, $user3->id, $user4->id]
2996         );
2998         // The person asking for the messages.
2999         $this->setUser($user1);
3001         // Send some messages back and forth.
3002         $time = time();
3003         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time);
3004         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Sup mang?', $time + 1);
3005         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Writing PHPUnit tests!', $time + 2);
3006         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 3);
3008         // Retrieve the messages.
3009         $result = core_message_external::get_conversation_messages($user1->id, $conversation->id);
3011         // We need to execute the return values cleaning process to simulate the web service server.
3012         $result = external_api::clean_returnvalue(core_message_external::get_conversation_messages_returns(),
3013             $result);
3015         // Check the results are correct.
3016         $this->assertEquals($conversation->id, $result['id']);
3018         // Confirm the members data is correct.
3019         $members = $result['members'];
3020         $this->assertCount(3, $members);
3021         $membersid = [$members[0]['id'], $members[1]['id'], $members[2]['id']];
3022         $this->assertContains($user1->id, $membersid);
3023         $this->assertContains($user2->id, $membersid);
3024         $this->assertContains($user3->id, $membersid);
3025         $this->assertNotContains($user4->id, $membersid);
3026         $this->assertNotContains($user5->id, $membersid);
3027         $membersfullnames = [$members[0]['fullname'], $members[1]['fullname'], $members[2]['fullname']];
3028         $this->assertContains(fullname($user1), $membersfullnames);
3029         $this->assertContains(fullname($user2), $membersfullnames);
3030         $this->assertContains(fullname($user3), $membersfullnames);
3031         $this->assertNotContains(fullname($user4), $membersfullnames);
3032         $this->assertNotContains(fullname($user5), $membersfullnames);
3034         // Confirm the messages data is correct.
3035         $messages = $result['messages'];
3036         $this->assertCount(4, $messages);
3038         $message1 = $messages[0];
3039         $message2 = $messages[1];
3040         $message3 = $messages[2];
3041         $message4 = $messages[3];
3043         $this->assertEquals($user1->id, $message1['useridfrom']);
3044         $this->assertContains('Yo!', $message1['text']);
3046         $this->assertEquals($user3->id, $message2['useridfrom']);
3047         $this->assertContains('Sup mang?', $message2['text']);
3049         $this->assertEquals($user2->id, $message3['useridfrom']);
3050         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
3052         $this->assertEquals($user1->id, $message4['useridfrom']);
3053         $this->assertContains('Word.', $message4['text']);
3054     }
3056     /**
3057      * Tests get_conversation_messages for retrieving messages using timefrom parameter.
3058      */
3059     public function test_get_conversation_messages_timefrom() {
3060         $this->resetAfterTest(true);
3062         // Create some users.
3063         $user1 = self::getDataGenerator()->create_user();
3064         $user2 = self::getDataGenerator()->create_user();
3065         $user3 = self::getDataGenerator()->create_user();
3066         $user4 = self::getDataGenerator()->create_user();
3068         // Create group conversation.
3069         $conversation = \core_message\api::create_conversation(
3070             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3071             [$user1->id, $user2->id, $user3->id]
3072         );
3074         // The person asking for the messages.
3075         $this->setUser($user1);
3077         // Send some messages back and forth.
3078         $time = time();
3079         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time - 4);
3080         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time - 3);
3081         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 3', $time - 2);
3082         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 4', $time - 1);
3084         // Retrieve the messages from $time - 3, which should be the 3 most recent messages.
3085         $result = core_message_external::get_conversation_messages($user1->id, $conversation->id, 0, 0, false, $time - 3);
3087         // We need to execute the return values cleaning process to simulate the web service server.
3088         $result = external_api::clean_returnvalue(core_message_external::get_conversation_messages_returns(),
3089             $result);
3091         // Check the results are correct.
3092         $this->assertEquals($conversation->id, $result['id']);
3094         // Confirm the messages data is correct.
3095         $messages = $result['messages'];
3096         $this->assertCount(3, $messages);
3098         $message1 = $messages[0];
3099         $message2 = $messages[1];
3100         $message3 = $messages[2];
3102         $this->assertContains('Message 2', $message1['text']);
3103         $this->assertContains('Message 3', $message2['text']);
3104         $this->assertContains('Message 4', $message3['text']);
3106         // Confirm the members data is correct.
3107         $members = $result['members'];
3108         $this->assertCount(1, $members);
3109         $this->assertEquals($user2->id, $members[0]['id']);
3110     }
3112     /**
3113      * Tests get_conversation_messages for retrieving messages as another user.
3114      */
3115     public function test_get_conversation_messages_as_other_user() {
3116         $this->resetAfterTest(true);
3118         // Set as admin.
3119         $this->setAdminUser();
3121         // Create some users.
3122         $user1 = self::getDataGenerator()->create_user();
3123         $user2 = self::getDataGenerator()->create_user();
3124         $user3 = self::getDataGenerator()->create_user();
3125         $user4 = self::getDataGenerator()->create_user();
3127         // Create group conversation.
3128         $conversation = \core_message\api::create_conversation(
3129             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3130             [$user1->id, $user2->id, $user3->id, $user4->id]
3131         );
3133         // Send some messages back and forth.
3134         $time = time();
3135         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time);
3136         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Sup mang?', $time + 1);
3137         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Writing PHPUnit tests!', $time + 2);
3138         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 3);
3140         // Retrieve the messages.
3141         $result = core_message_external::get_conversation_messages($user1->id, $conversation->id);
3143         // We need to execute the return values cleaning process to simulate the web service server.
3144         $result = external_api::clean_returnvalue(core_message_external::get_conversation_messages_returns(),
3145             $result);
3147         // Check the results are correct.
3148         $this->assertEquals($conversation->id, $result['id']);
3150         // Confirm the members data is correct.
3151         $members = $result['members'];
3152         $this->assertCount(3, $members);
3153         $membersid = [$members[0]['id'], $members[1]['id'], $members[2]['id']];
3154         $this->assertContains($user1->id, $membersid);
3155         $this->assertContains($user2->id, $membersid);
3156         $this->assertContains($user3->id, $membersid);
3157         $this->assertNotContains($user4->id, $membersid);
3159         // Confirm the message data is correct.
3160         $messages = $result['messages'];
3161         $this->assertCount(4, $messages);
3163         $message1 = $messages[0];
3164         $message2 = $messages[1];
3165         $message3 = $messages[2];
3166         $message4 = $messages[3];
3168         $this->assertEquals($user1->id, $message1['useridfrom']);
3169         $this->assertContains('Yo!', $message1['text']);
3171         $this->assertEquals($user3->id, $message2['useridfrom']);
3172         $this->assertContains('Sup mang?', $message2['text']);
3174         $this->assertEquals($user2->id, $message3['useridfrom']);
3175         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
3177         $this->assertEquals($user1->id, $message4['useridfrom']);
3178         $this->assertContains('Word.', $message4['text']);
3179     }
3181     /**
3182      * Tests get_conversation_messages for retrieving messages as another user without the proper capabilities.
3183      */
3184     public function test_get_conversation_messages_as_other_user_without_cap() {
3185         $this->resetAfterTest(true);
3187         // Create some users.
3188         $user1 = self::getDataGenerator()->create_user();
3189         $user2 = self::getDataGenerator()->create_user();
3190         $user3 = self::getDataGenerator()->create_user();
3191         $user4 = self::getDataGenerator()->create_user();
3193         // Create group conversation.
3194         $conversation = \core_message\api::create_conversation(
3195             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3196             [$user1->id, $user2->id, $user3->id, $user4->id]
3197         );
3199         // The person asking for the messages for another user.
3200         $this->setUser($user1);
3202         // Ensure an exception is thrown.
3203         $this->expectException('moodle_exception');
3204         core_message_external::get_conversation_messages($user2->id, $conversation->id);
3205     }
3207     /**
3208      * Tests get_conversation_messages for retrieving messages with messaging disabled.
3209      */
3210     public function test_get_conversation_messages_messaging_disabled() {
3211         $this->resetAfterTest(true);
3213         // Create some skeleton data just so we can call the WS.
3214         $user1 = self::getDataGenerator()->create_user();
3215         $user2 = self::getDataGenerator()->create_user();
3216         $user3 = self::getDataGenerator()->create_user();
3217         $user4 = self::getDataGenerator()->create_user();
3219         // Create group conversation.
3220         $conversation = \core_message\api::create_conversation(
3221             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3222             [$user1->id, $user2->id, $user3->id, $user4->id]
3223         );
3225         // The person asking for the messages for another user.
3226         $this->setUser($user1);
3228         // Disable messaging.
3229         set_config('messaging', 0);
3231         // Ensure an exception is thrown.
3232         $this->expectException('moodle_exception');
3233         core_message_external::get_conversation_messages($user1->id, $conversation->id);
3234     }
3236     /**
3237      * Tests retrieving most recent message.
3238      */
3239     public function test_messagearea_get_most_recent_message() {
3240         $this->resetAfterTest(true);
3242         // Create some users.
3243         $user1 = self::getDataGenerator()->create_user();
3244         $user2 = self::getDataGenerator()->create_user();
3246         // The person doing the search.
3247         $this->setUser($user1);
3249         // Send some messages back and forth.
3250         $time = time();
3251         $this->send_message($user1, $user2, 'Yo!', 0, $time);
3252         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3253         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3254         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3256         // Get the most recent message.
3257         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
3258         $this->assertDebuggingCalledCount(3);
3260         // We need to execute the return values cleaning process to simulate the web service server.
3261         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
3262             $result);
3264         // Check the results are correct.
3265         $this->assertEquals($user2->id, $result['useridfrom']);
3266         $this->assertEquals($user1->id, $result['useridto']);
3267         $this->assertContains('Word.', $result['text']);
3268     }
3270     /**
3271      * Tests retrieving most recent message as another user.
3272      */
3273     public function test_messagearea_get_most_recent_message_as_other_user() {
3274         $this->resetAfterTest(true);
3276         // The person doing the search.
3277         $this->setAdminUser();
3279         // Create some users.
3280         $user1 = self::getDataGenerator()->create_user();
3281         $user2 = self::getDataGenerator()->create_user();
3283         // Send some messages back and forth.
3284         $time = time();
3285         $this->send_message($user1, $user2, 'Yo!', 0, $time);
3286         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3287         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3288         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3290         // Get the most recent message.
3291         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
3292         $this->assertDebuggingCalledCount(3);
3294         // We need to execute the return values cleaning process to simulate the web service server.
3295         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
3296             $result);
3298         // Check the results are correct.
3299         $this->assertEquals($user2->id, $result['useridfrom']);
3300         $this->assertEquals($user1->id, $result['useridto']);
3301         $this->assertContains('Word.', $result['text']);
3302     }
3304     /**
3305      * Tests retrieving most recent message as another user without the proper capabilities.
3306      */
3307     public function test_messagearea_get_most_recent_message_as_other_user_without_cap() {
3308         $this->resetAfterTest(true);
3310         // Create some users.
3311         $user1 = self::getDataGenerator()->create_user();
3312         $user2 = self::getDataGenerator()->create_user();
3313         $user3 = self::getDataGenerator()->create_user();
3315         // The person asking for the most recent message for another user.
3316         $this->setUser($user1);
3318         // Ensure an exception is thrown.
3319         $this->expectException('moodle_exception');
3320         core_message_external::data_for_messagearea_get_most_recent_message($user2->id, $user3->id);
3321     }
3323     /**
3324      * Tests retrieving most recent message with messaging disabled.
3325      */
3326     public function test_messagearea_get_most_recent_message_messaging_disabled() {
3327         global $CFG;
3329         $this->resetAfterTest(true);
3331         // Create some skeleton data just so we can call the WS.
3332         $user1 = self::getDataGenerator()->create_user();
3333         $user2 = self::getDataGenerator()->create_user();
3335         // The person asking for the most recent message.
3336         $this->setUser($user1);
3338         // Disable messaging.
3339         $CFG->messaging = 0;
3341         // Ensure an exception is thrown.
3342         $this->expectException('moodle_exception');
3343         core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
3344     }
3346     /**
3347      * Tests retrieving a user's profile.
3348      */
3349     public function test_messagearea_get_profile() {
3350         $this->resetAfterTest(true);
3352         // Create some users.
3353         $user1 = self::getDataGenerator()->create_user();
3354         $user2 = self::getDataGenerator()->create_user();
3356         // The person asking for the profile information.
3357         $this->setUser($user1);
3359         // Get the profile.
3360         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
3362         // We need to execute the return values cleaning process to simulate the web service server.
3363         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_profile_returns(),
3364             $result);
3366         $this->assertEquals($user2->id, $result['userid']);
3367         $this->assertEmpty($result['email']);
3368         $this->assertEmpty($result['country']);
3369         $this->assertEmpty($result['city']);
3370         $this->assertEquals(fullname($user2), $result['fullname']);
3371         $this->assertNull($result['isonline']);
3372         $this->assertFalse($result['isblocked']);
3373         $this->assertFalse($result['iscontact']);
3374     }
3376     /**
3377      * Tests retrieving a user's profile as another user.
3378      */
3379     public function test_messagearea_profile_as_other_user() {
3380         $this->resetAfterTest(true);
3382         // The person asking for the profile information.
3383         $this->setAdminUser();
3385         // Create some users.
3386         $user1 = self::getDataGenerator()->create_user();
3388         $user2 = new stdClass();
3389         $user2->country = 'AU';
3390         $user2->city = 'Perth';
3391         $user2 = self::getDataGenerator()->create_user($user2);
3393         // Get the profile.
3394         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
3396         // We need to execute the return values cleaning process to simulate t