MDL-63716 course: less user_accesstime_log() calls
[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_data_for_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_data_for_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_data_for_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         $this->assertDebuggingCalled();
1964     }
1966     /**
1967      * Tests searching users in course with messaging disabled.
1968      */
1969     public function test_data_for_messagearea_search_users_in_course_messaging_disabled() {
1970         global $CFG;
1972         $this->resetAfterTest(true);
1974         // Create some skeleton data just so we can call the WS..
1975         $user = self::getDataGenerator()->create_user();
1976         $course = $this->getDataGenerator()->create_course();
1978         // The person doing the search for another user.
1979         $this->setUser($user);
1981         // Disable messaging.
1982         $CFG->messaging = 0;
1984         // Ensure an exception is thrown.
1985         $this->expectException('moodle_exception');
1986         core_message_external::data_for_messagearea_search_users_in_course($user->id, $course->id, 'User');
1987         $this->assertDebuggingCalled();
1988     }
1990     /**
1991      * Tests searching users.
1992      */
1993     public function test_data_for_messagearea_search_users() {
1994         $this->resetAfterTest(true);
1996         // Create some users.
1997         $user1 = new stdClass();
1998         $user1->firstname = 'User';
1999         $user1->lastname = 'One';
2000         $user1 = self::getDataGenerator()->create_user($user1);
2002         // Set as the user performing the search.
2003         $this->setUser($user1);
2005         $user2 = new stdClass();
2006         $user2->firstname = 'User search';
2007         $user2->lastname = 'Two';
2008         $user2 = self::getDataGenerator()->create_user($user2);
2010         $user3 = new stdClass();
2011         $user3->firstname = 'User search';
2012         $user3->lastname = 'Three';
2013         $user3 = self::getDataGenerator()->create_user($user3);
2015         $user4 = new stdClass();
2016         $user4->firstname = 'User';
2017         $user4->lastname = 'Four';
2018         $user4 = self::getDataGenerator()->create_user($user4);
2020         $user5 = new stdClass();
2021         $user5->firstname = 'User search';
2022         $user5->lastname = 'Five';
2023         $user5 = self::getDataGenerator()->create_user($user5);
2025         $user6 = new stdClass();
2026         $user6->firstname = 'User';
2027         $user6->lastname = 'Six';
2028         $user6 = self::getDataGenerator()->create_user($user6);
2030         // Create some courses.
2031         $course1 = new stdClass();
2032         $course1->fullname = 'Course search';
2033         $course1->shortname = 'One';
2034         $course1 = $this->getDataGenerator()->create_course($course1);
2036         $course2 = new stdClass();
2037         $course2->fullname = 'Course';
2038         $course2->shortname = 'Two';
2039         $course2 = $this->getDataGenerator()->create_course($course2);
2041         $course3 = new stdClass();
2042         $course3->fullname = 'Course';
2043         $course3->shortname = 'Three search';
2044         $course3 = $this->getDataGenerator()->create_course($course3);
2046         $course4 = new stdClass();
2047         $course4->fullname = 'Course Four';
2048         $course4->shortname = 'CF100';
2049         $course4 = $this->getDataGenerator()->create_course($course4);
2051         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
2052         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'student');
2053         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 'student');
2055         // Add some users as contacts.
2056         \core_message\api::add_contact($user1->id, $user2->id);
2057         \core_message\api::add_contact($user1->id, $user3->id);
2058         \core_message\api::add_contact($user1->id, $user4->id);
2060         // Perform a search $CFG->messagingallusers setting enabled.
2061         set_config('messagingallusers', 1);
2062         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2064         // We need to execute the return values cleaning process to simulate the web service server.
2065         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2066             $result);
2068         // Confirm that we returns contacts, courses and non-contacts.
2069         $contacts = $result['contacts'];
2070         $courses = $result['courses'];
2071         $noncontacts = $result['noncontacts'];
2073         // Check that we retrieved the correct contacts.
2074         $this->assertCount(2, $contacts);
2075         $this->assertEquals($user3->id, $contacts[0]['userid']);
2076         $this->assertEquals($user2->id, $contacts[1]['userid']);
2078         // Check that we retrieved the correct courses.
2079         $this->assertCount(2, $courses);
2080         $this->assertEquals($course3->id, $courses[0]['id']);
2081         $this->assertEquals($course1->id, $courses[1]['id']);
2083         // Check that we retrieved the correct non-contacts.
2084         $this->assertCount(1, $noncontacts);
2085         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2086     }
2088     /**
2089      * Tests searching users as another user.
2090      */
2091     public function test_data_for_messagearea_search_users_as_other_user() {
2092         $this->resetAfterTest(true);
2094         // The person doing the search.
2095         $this->setAdminUser();
2097         // Create some users.
2098         $user1 = new stdClass();
2099         $user1->firstname = 'User';
2100         $user1->lastname = 'One';
2101         $user1 = self::getDataGenerator()->create_user($user1);
2103         $user2 = new stdClass();
2104         $user2->firstname = 'User search';
2105         $user2->lastname = 'Two';
2106         $user2 = self::getDataGenerator()->create_user($user2);
2108         $user3 = new stdClass();
2109         $user3->firstname = 'User search';
2110         $user3->lastname = 'Three';
2111         $user3 = self::getDataGenerator()->create_user($user3);
2113         $user4 = new stdClass();
2114         $user4->firstname = 'User';
2115         $user4->lastname = 'Four';
2116         $user4 = self::getDataGenerator()->create_user($user4);
2118         $user5 = new stdClass();
2119         $user5->firstname = 'User search';
2120         $user5->lastname = 'Five';
2121         $user5 = self::getDataGenerator()->create_user($user5);
2123         $user6 = new stdClass();
2124         $user6->firstname = 'User';
2125         $user6->lastname = 'Six';
2126         $user6 = self::getDataGenerator()->create_user($user6);
2128         // Create some courses.
2129         $course1 = new stdClass();
2130         $course1->fullname = 'Course search';
2131         $course1->shortname = 'One';
2132         $course1 = $this->getDataGenerator()->create_course($course1);
2134         $course2 = new stdClass();
2135         $course2->fullname = 'Course';
2136         $course2->shortname = 'Two';
2137         $course2 = $this->getDataGenerator()->create_course($course2);
2139         $course3 = new stdClass();
2140         $course3->fullname = 'Course';
2141         $course3->shortname = 'Three search';
2142         $course3 = $this->getDataGenerator()->create_course($course3);
2144         // Add some users as contacts.
2145         \core_message\api::add_contact($user1->id, $user2->id);
2146         \core_message\api::add_contact($user1->id, $user3->id);
2147         \core_message\api::add_contact($user1->id, $user4->id);
2149         // Perform a search $CFG->messagingallusers setting enabled.
2150         set_config('messagingallusers', 1);
2151         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2153         // We need to execute the return values cleaning process to simulate the web service server.
2154         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2155             $result);
2157         // Confirm that we returns contacts, courses and non-contacts.
2158         $contacts = $result['contacts'];
2159         $courses = $result['courses'];
2160         $noncontacts = $result['noncontacts'];
2162         // Check that we retrieved the correct contacts.
2163         $this->assertCount(2, $contacts);
2164         $this->assertEquals($user3->id, $contacts[0]['userid']);
2165         $this->assertEquals($user2->id, $contacts[1]['userid']);
2167         // Check that we retrieved the correct courses.
2168         $this->assertCount(0, $courses);
2170         // Check that we retrieved the correct non-contacts.
2171         $this->assertCount(1, $noncontacts);
2172         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2173     }
2175     /**
2176      * Tests searching users as another user without the proper capabilities.
2177      */
2178     public function test_data_for_messagearea_search_users_as_other_user_without_cap() {
2179         $this->resetAfterTest(true);
2181         // Create some users.
2182         $user1 = self::getDataGenerator()->create_user();
2183         $user2 = self::getDataGenerator()->create_user();
2185         // The person doing the search for another user.
2186         $this->setUser($user1);
2188         // Ensure an exception is thrown.
2189         $this->expectException('moodle_exception');
2190         core_message_external::data_for_messagearea_search_users($user2->id, 'User');
2191         $this->assertDebuggingCalled();
2192     }
2194     /**
2195      * Tests searching users with messaging disabled.
2196      */
2197     public function test_data_for_messagearea_search_users_messaging_disabled() {
2198         global $CFG;
2200         $this->resetAfterTest(true);
2202         // Create some skeleton data just so we can call the WS.
2203         $user = self::getDataGenerator()->create_user();
2205         // The person doing the search.
2206         $this->setUser($user);
2208         // Disable messaging.
2209         $CFG->messaging = 0;
2211         // Ensure an exception is thrown.
2212         $this->expectException('moodle_exception');
2213         core_message_external::data_for_messagearea_search_users($user->id, 'User');
2214         $this->assertDebuggingCalled();
2215     }
2217     /**
2218      * Tests searching users.
2219      */
2220     public function test_message_search_users() {
2221         $this->resetAfterTest(true);
2223         // Create some users.
2224         $user1 = new stdClass();
2225         $user1->firstname = 'User search';
2226         $user1->lastname = 'One';
2227         $user1 = self::getDataGenerator()->create_user($user1);
2228         // Set as the user performing the search.
2229         $this->setUser($user1);
2231         $user2 = new stdClass();
2232         $user2->firstname = 'User search';
2233         $user2->lastname = 'Two';
2234         $user2 = self::getDataGenerator()->create_user($user2);
2236         $user3 = new stdClass();
2237         $user3->firstname = 'User search';
2238         $user3->lastname = 'Three';
2239         $user3 = self::getDataGenerator()->create_user($user3);
2241         $user4 = new stdClass();
2242         $user4->firstname = 'User';
2243         $user4->lastname = 'Four';
2244         $user4 = self::getDataGenerator()->create_user($user4);
2246         $user5 = new stdClass();
2247         $user5->firstname = 'User search';
2248         $user5->lastname = 'Five';
2249         $user5 = self::getDataGenerator()->create_user($user5);
2251         $user6 = new stdClass();
2252         $user6->firstname = 'User search';
2253         $user6->lastname = 'Six';
2254         $user6 = self::getDataGenerator()->create_user($user6);
2256         $user7 = new stdClass();
2257         $user7->firstname = 'User search';
2258         $user7->lastname = 'Seven';
2259         $user7 = self::getDataGenerator()->create_user($user7);
2261         // Add some users as contacts.
2262         \core_message\api::add_contact($user1->id, $user2->id);
2263         \core_message\api::add_contact($user3->id, $user1->id);
2264         \core_message\api::add_contact($user1->id, $user4->id);
2266         // Create private conversations with some users.
2267         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2268             array($user1->id, $user6->id));
2269         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2270             array($user7->id, $user1->id));
2272         // Perform a search $CFG->messagingallusers setting enabled.
2273         set_config('messagingallusers', 1);
2274         $result = core_message_external::message_search_users($user1->id, 'search');
2276         // We need to execute the return values cleaning process to simulate the web service server.
2277         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(),
2278             $result);
2280         // Confirm that we returns contacts and non-contacts.
2281         $contacts = $result['contacts'];
2282         $noncontacts = $result['noncontacts'];
2284         // Check that we retrieved the correct contacts.
2285         $this->assertCount(2, $contacts);
2286         $this->assertEquals($user3->id, $contacts[0]['id']);
2287         $this->assertEquals($user2->id, $contacts[1]['id']);
2289         // Check that we retrieved the correct non-contacts.
2290         $this->assertCount(3, $noncontacts);
2291         $this->assertEquals($user5->id, $noncontacts[0]['id']);
2292         $this->assertEquals($user7->id, $noncontacts[1]['id']);
2293         $this->assertEquals($user6->id, $noncontacts[2]['id']);
2295         // Perform a search $CFG->messagingallusers setting disabled.
2296         set_config('messagingallusers', 0);
2297         $result = core_message_external::message_search_users($user1->id, 'search');
2299         // We need to execute the return values cleaning process to simulate the web service server.
2300         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(),
2301             $result);
2303         // Confirm that we returns contacts and non-contacts.
2304         $contacts = $result['contacts'];
2305         $noncontacts = $result['noncontacts'];
2307         // Check that we retrieved the correct contacts.
2308         $this->assertCount(2, $contacts);
2309         $this->assertEquals($user3->id, $contacts[0]['id']);
2310         $this->assertEquals($user2->id, $contacts[1]['id']);
2312         // Check that we retrieved the correct non-contacts.
2313         $this->assertCount(2, $noncontacts);
2314         $this->assertEquals($user7->id, $noncontacts[0]['id']);
2315         $this->assertEquals($user6->id, $noncontacts[1]['id']);
2316     }
2318     /**
2319      * Tests searching users as another user.
2320      */
2321     public function test_message_search_users_as_other_user() {
2322         $this->resetAfterTest(true);
2324         // The person doing the search.
2325         $this->setAdminUser();
2327         // Create some users.
2328         $user1 = new stdClass();
2329         $user1->firstname = 'User search';
2330         $user1->lastname = 'One';
2331         $user1 = self::getDataGenerator()->create_user($user1);
2333         $user2 = new stdClass();
2334         $user2->firstname = 'User search';
2335         $user2->lastname = 'Two';
2336         $user2 = self::getDataGenerator()->create_user($user2);
2338         $user3 = new stdClass();
2339         $user3->firstname = 'User search';
2340         $user3->lastname = 'Three';
2341         $user3 = self::getDataGenerator()->create_user($user3);
2343         $user4 = new stdClass();
2344         $user4->firstname = 'User';
2345         $user4->lastname = 'Four';
2346         $user4 = self::getDataGenerator()->create_user($user4);
2348         $user5 = new stdClass();
2349         $user5->firstname = 'User search';
2350         $user5->lastname = 'Five';
2351         $user5 = self::getDataGenerator()->create_user($user5);
2353         $user6 = new stdClass();
2354         $user6->firstname = 'User search';
2355         $user6->lastname = 'Six';
2356         $user6 = self::getDataGenerator()->create_user($user6);
2358         $user7 = new stdClass();
2359         $user7->firstname = 'User search';
2360         $user7->lastname = 'Seven';
2361         $user7 = self::getDataGenerator()->create_user($user7);
2363         // Add some users as contacts.
2364         \core_message\api::add_contact($user1->id, $user2->id);
2365         \core_message\api::add_contact($user3->id, $user1->id);
2366         \core_message\api::add_contact($user1->id, $user4->id);
2368         // Create private conversations with some users.
2369         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2370             array($user1->id, $user6->id));
2371         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2372             array($user7->id, $user1->id));
2374         // Perform a search $CFG->messagingallusers setting enabled.
2375         set_config('messagingallusers', 1);
2376         $result = core_message_external::message_search_users($user1->id, 'search');
2378         // We need to execute the return values cleaning process to simulate the web service server.
2379         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(),
2380             $result);
2382         // Confirm that we returns contacts and non-contacts.
2383         $contacts = $result['contacts'];
2384         $noncontacts = $result['noncontacts'];
2386         // Check that we retrieved the correct contacts.
2387         $this->assertCount(2, $contacts);
2388         $this->assertEquals($user3->id, $contacts[0]['id']);
2389         $this->assertEquals($user2->id, $contacts[1]['id']);
2391         // Check that we retrieved the correct non-contacts.
2392         $this->assertCount(3, $noncontacts);
2393         $this->assertEquals($user5->id, $noncontacts[0]['id']);
2394         $this->assertEquals($user7->id, $noncontacts[1]['id']);
2395         $this->assertEquals($user6->id, $noncontacts[2]['id']);
2397         // Perform a search $CFG->messagingallusers setting disabled.
2398         set_config('messagingallusers', 0);
2399         $result = core_message_external::message_search_users($user1->id, 'search');
2401         // We need to execute the return values cleaning process to simulate the web service server.
2402         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(),
2403             $result);
2405         // Confirm that we returns contacts and non-contacts.
2406         $contacts = $result['contacts'];
2407         $noncontacts = $result['noncontacts'];
2409         // Check that we retrieved the correct contacts.
2410         $this->assertCount(2, $contacts);
2411         $this->assertEquals($user3->id, $contacts[0]['id']);
2412         $this->assertEquals($user2->id, $contacts[1]['id']);
2414         // Check that we retrieved the correct non-contacts.
2415         $this->assertCount(2, $noncontacts);
2416         $this->assertEquals($user7->id, $noncontacts[0]['id']);
2417         $this->assertEquals($user6->id, $noncontacts[1]['id']);
2418     }
2420     /**
2421      * Tests searching users as another user without the proper capabilities.
2422      */
2423     public function test_message_search_users_as_other_user_without_cap() {
2424         $this->resetAfterTest(true);
2426         // Create some users.
2427         $user1 = self::getDataGenerator()->create_user();
2428         $user2 = self::getDataGenerator()->create_user();
2430         // The person doing the search for another user.
2431         $this->setUser($user1);
2433         // Ensure an exception is thrown.
2434         $this->expectException('moodle_exception');
2435         core_message_external::message_search_users($user2->id, 'User');
2436         $this->assertDebuggingCalled();
2437     }
2439     /**
2440      * Tests searching users with and without conversations.
2441      */
2442     public function test_message_search_users_with_and_without_conversations() {
2443         $this->resetAfterTest(true);
2445         // Create some users.
2446         $user1 = new stdClass();
2447         $user1->firstname = 'User search';
2448         $user1->lastname = 'One';
2449         $user1 = self::getDataGenerator()->create_user($user1);
2451         // Set as the user performing the search.
2452         $this->setUser($user1);
2454         $user2 = new stdClass();
2455         $user2->firstname = 'User search';
2456         $user2->lastname = 'Two';
2457         $user2 = self::getDataGenerator()->create_user($user2);
2459         $user3 = new stdClass();
2460         $user3->firstname = 'User search';
2461         $user3->lastname = 'Three';
2462         $user3 = self::getDataGenerator()->create_user($user3);
2464         $user4 = new stdClass();
2465         $user4->firstname = 'User';
2466         $user4->lastname = 'Four';
2467         $user4 = self::getDataGenerator()->create_user($user4);
2469         $user5 = new stdClass();
2470         $user5->firstname = 'User search';
2471         $user5->lastname = 'Five';
2472         $user5 = self::getDataGenerator()->create_user($user5);
2474         // Add a user as contact.
2475         \core_message\api::add_contact($user1->id, $user2->id);
2477         // Create private conversations with some users.
2478         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2479             array($user1->id, $user2->id));
2480         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2481             array($user3->id, $user1->id));
2483         // Create a group conversation with users.
2484         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2485             array($user1->id, $user2->id, $user4->id),
2486             'Project chat');
2488         // Perform a search $CFG->messagingallusers setting enabled.
2489         set_config('messagingallusers', 1);
2490         $result = core_message_external::message_search_users($user1->id, 'search');
2492         // We need to execute the return values cleaning process to simulate the web service server.
2493         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(),
2494             $result);
2496         // Confirm that we returns contacts and non-contacts.
2497         $contacts = $result['contacts'];
2498         $noncontacts = $result['noncontacts'];
2500         // Check that we retrieved the correct contacts.
2501         $this->assertCount(1, $contacts);
2503         // Check that we retrieved the correct conversations for contacts.
2504         $this->assertCount(2, $contacts[0]['conversations']);
2506         // Check that we retrieved the correct non-contacts.
2507         $this->assertCount(2, $noncontacts);
2508         $this->assertEquals($user5->id, $noncontacts[0]['id']);
2509         $this->assertEquals($user3->id, $noncontacts[1]['id']);
2511         // Check that we retrieved the correct conversations for non-contacts.
2512         $this->assertCount(0, $noncontacts[0]['conversations']);
2513         $this->assertCount(1, $noncontacts[1]['conversations']);
2514     }
2516     /**
2517      * Tests searching users with messaging disabled.
2518      */
2519     public function test_message_search_users_messaging_disabled() {
2520         $this->resetAfterTest(true);
2522         // Create some skeleton data just so we can call the WS.
2523         $user = self::getDataGenerator()->create_user();
2525         // The person doing the search.
2526         $this->setUser($user);
2528         // Disable messaging.
2529         set_config('messaging', 0);
2531         // Ensure an exception is thrown.
2532         $this->expectException('moodle_exception');
2533         core_message_external::message_search_users($user->id, 'User');
2534         $this->assertDebuggingCalled();
2535     }
2537     /**
2538      * Tests searching messages.
2539      */
2540     public function test_messagearea_search_messages() {
2541         $this->resetAfterTest(true);
2543         // Create some users.
2544         $user1 = self::getDataGenerator()->create_user();
2545         $user2 = self::getDataGenerator()->create_user();
2547         // The person doing the search.
2548         $this->setUser($user1);
2550         // Send some messages back and forth.
2551         $time = time();
2552         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2553         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2554         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2555         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2557         // Perform a search.
2558         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2560         // We need to execute the return values cleaning process to simulate the web service server.
2561         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2562             $result);
2564         // Confirm the data is correct.
2565         $messages = $result['contacts'];
2566         $this->assertCount(2, $messages);
2568         $message1 = $messages[0];
2569         $message2 = $messages[1];
2571         $this->assertEquals($user2->id, $message1['userid']);
2572         $this->assertEquals(fullname($user2), $message1['fullname']);
2573         $this->assertTrue($message1['ismessaging']);
2574         $this->assertFalse($message1['sentfromcurrentuser']);
2575         $this->assertEquals('Word.', $message1['lastmessage']);
2576         $this->assertNotEmpty($message1['messageid']);
2577         $this->assertNull($message1['isonline']);
2578         $this->assertFalse($message1['isread']);
2579         $this->assertFalse($message1['isblocked']);
2580         $this->assertNull($message1['unreadcount']);
2582         $this->assertEquals($user2->id, $message2['userid']);
2583         $this->assertEquals(fullname($user2), $message2['fullname']);
2584         $this->assertTrue($message2['ismessaging']);
2585         $this->assertTrue($message2['sentfromcurrentuser']);
2586         $this->assertEquals('Yo!', $message2['lastmessage']);
2587         $this->assertNotEmpty($message2['messageid']);
2588         $this->assertNull($message2['isonline']);
2589         $this->assertTrue($message2['isread']);
2590         $this->assertFalse($message2['isblocked']);
2591         $this->assertNull($message2['unreadcount']);
2592     }
2594     /**
2595      * Tests searching messages as another user.
2596      */
2597     public function test_messagearea_search_messages_as_other_user() {
2598         $this->resetAfterTest(true);
2600         // The person doing the search.
2601         $this->setAdminUser();
2603         // Create some users.
2604         $user1 = self::getDataGenerator()->create_user();
2605         $user2 = self::getDataGenerator()->create_user();
2607         // Send some messages back and forth.
2608         $time = time();
2609         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2610         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2611         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2612         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2614         // Perform a search.
2615         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2617         // We need to execute the return values cleaning process to simulate the web service server.
2618         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2619             $result);
2621         // Confirm the data is correct.
2622         $messages = $result['contacts'];
2623         $this->assertCount(2, $messages);
2625         $message1 = $messages[0];
2626         $message2 = $messages[1];
2628         $this->assertEquals($user2->id, $message1['userid']);
2629         $this->assertEquals(fullname($user2), $message1['fullname']);
2630         $this->assertTrue($message1['ismessaging']);
2631         $this->assertFalse($message1['sentfromcurrentuser']);
2632         $this->assertEquals('Word.', $message1['lastmessage']);
2633         $this->assertNotEmpty($message1['messageid']);
2634         $this->assertFalse($message1['isonline']);
2635         $this->assertFalse($message1['isread']);
2636         $this->assertFalse($message1['isblocked']);
2637         $this->assertNull($message1['unreadcount']);
2639         $this->assertEquals($user2->id, $message2['userid']);
2640         $this->assertEquals(fullname($user2), $message2['fullname']);
2641         $this->assertTrue($message2['ismessaging']);
2642         $this->assertTrue($message2['sentfromcurrentuser']);
2643         $this->assertEquals('Yo!', $message2['lastmessage']);
2644         $this->assertNotEmpty($message2['messageid']);
2645         $this->assertFalse($message2['isonline']);
2646         $this->assertTrue($message2['isread']);
2647         $this->assertFalse($message2['isblocked']);
2648         $this->assertNull($message2['unreadcount']);
2649     }
2651     /**
2652      * Tests searching messages as another user without the proper capabilities.
2653      */
2654     public function test_messagearea_search_messages_as_other_user_without_cap() {
2655         $this->resetAfterTest(true);
2657         // Create some users.
2658         $user1 = self::getDataGenerator()->create_user();
2659         $user2 = self::getDataGenerator()->create_user();
2661         // The person doing the search for another user.
2662         $this->setUser($user1);
2664         // Ensure an exception is thrown.
2665         $this->expectException('moodle_exception');
2666         core_message_external::data_for_messagearea_search_messages($user2->id, 'Search');
2667     }
2669     /**
2670      * Tests searching messages with messaging disabled
2671      */
2672     public function test_messagearea_search_messages_messaging_disabled() {
2673         global $CFG;
2675         $this->resetAfterTest(true);
2677         // Create some skeleton data just so we can call the WS.
2678         $user = self::getDataGenerator()->create_user();
2680         // The person doing the search .
2681         $this->setUser($user);
2683         // Disable messaging.
2684         $CFG->messaging = 0;
2686         // Ensure an exception is thrown.
2687         $this->expectException('moodle_exception');
2688         core_message_external::data_for_messagearea_search_messages($user->id, 'Search');
2689     }
2691     /**
2692      * Tests retrieving conversations.
2693      */
2694     public function test_messagearea_conversations() {
2695         $this->resetAfterTest(true);
2697         // Create some users.
2698         $user1 = self::getDataGenerator()->create_user();
2699         $user2 = self::getDataGenerator()->create_user();
2700         $user3 = self::getDataGenerator()->create_user();
2701         $user4 = self::getDataGenerator()->create_user();
2703         // The person retrieving the conversations.
2704         $this->setUser($user1);
2706         // Send some messages back and forth, have some different conversations with different users.
2707         $time = time();
2708         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2709         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2710         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2711         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2713         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2714         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2715         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2716         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2718         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2719         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2720         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2722         // Retrieve the conversations.
2723         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2725         // We need to execute the return values cleaning process to simulate the web service server.
2726         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2727             $result);
2729         // Confirm the data is correct.
2730         $messages = $result['contacts'];
2731         $this->assertCount(3, $messages);
2733         $message1 = $messages[0];
2734         $message2 = $messages[1];
2735         $message3 = $messages[2];
2737         $this->assertEquals($user4->id, $message1['userid']);
2738         $this->assertTrue($message1['ismessaging']);
2739         $this->assertTrue($message1['sentfromcurrentuser']);
2740         $this->assertEquals('Dope.', $message1['lastmessage']);
2741         $this->assertEquals($messageid3, $message1['messageid']);
2742         $this->assertNull($message1['isonline']);
2743         $this->assertFalse($message1['isread']);
2744         $this->assertFalse($message1['isblocked']);
2745         $this->assertEquals(1, $message1['unreadcount']);
2747         $this->assertEquals($user3->id, $message2['userid']);
2748         $this->assertTrue($message2['ismessaging']);
2749         $this->assertFalse($message2['sentfromcurrentuser']);
2750         $this->assertEquals('Cool.', $message2['lastmessage']);
2751         $this->assertEquals($messageid2, $message2['messageid']);
2752         $this->assertNull($message2['isonline']);
2753         $this->assertFalse($message2['isread']);
2754         $this->assertFalse($message2['isblocked']);
2755         $this->assertEquals(2, $message2['unreadcount']);
2757         $this->assertEquals($user2->id, $message3['userid']);
2758         $this->assertTrue($message3['ismessaging']);
2759         $this->assertFalse($message3['sentfromcurrentuser']);
2760         $this->assertEquals('Word.', $message3['lastmessage']);
2761         $this->assertEquals($messageid1, $message3['messageid']);
2762         $this->assertNull($message3['isonline']);
2763         $this->assertFalse($message3['isread']);
2764         $this->assertFalse($message3['isblocked']);
2765         $this->assertEquals(2, $message3['unreadcount']);
2766     }
2768     /**
2769      * Tests retrieving conversations as another user.
2770      */
2771     public function test_messagearea_conversations_as_other_user() {
2772         $this->resetAfterTest(true);
2774         // Set as admin.
2775         $this->setAdminUser();
2777         // Create some users.
2778         $user1 = self::getDataGenerator()->create_user();
2779         $user2 = self::getDataGenerator()->create_user();
2780         $user3 = self::getDataGenerator()->create_user();
2781         $user4 = self::getDataGenerator()->create_user();
2783         // Send some messages back and forth, have some different conversations with different users.
2784         $time = time();
2785         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2786         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2787         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2788         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2790         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2791         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2792         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2793         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2795         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2796         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2797         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2799         // Retrieve the conversations.
2800         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2802         // We need to execute the return values cleaning process to simulate the web service server.
2803         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2804             $result);
2806         // Confirm the data is correct.
2807         $messages = $result['contacts'];
2808         $this->assertCount(3, $messages);
2810         $message1 = $messages[0];
2811         $message2 = $messages[1];
2812         $message3 = $messages[2];
2814         $this->assertEquals($user4->id, $message1['userid']);
2815         $this->assertTrue($message1['ismessaging']);
2816         $this->assertTrue($message1['sentfromcurrentuser']);
2817         $this->assertEquals('Dope.', $message1['lastmessage']);
2818         $this->assertEquals($messageid3, $message1['messageid']);
2819         $this->assertFalse($message1['isonline']);
2820         $this->assertFalse($message1['isread']);
2821         $this->assertFalse($message1['isblocked']);
2822         $this->assertEquals(1, $message1['unreadcount']);
2824         $this->assertEquals($user3->id, $message2['userid']);
2825         $this->assertTrue($message2['ismessaging']);
2826         $this->assertFalse($message2['sentfromcurrentuser']);
2827         $this->assertEquals('Cool.', $message2['lastmessage']);
2828         $this->assertEquals($messageid2, $message2['messageid']);
2829         $this->assertFalse($message2['isonline']);
2830         $this->assertFalse($message2['isread']);
2831         $this->assertFalse($message2['isblocked']);
2832         $this->assertEquals(2, $message2['unreadcount']);
2834         $this->assertEquals($user2->id, $message3['userid']);
2835         $this->assertTrue($message3['ismessaging']);
2836         $this->assertFalse($message3['sentfromcurrentuser']);
2837         $this->assertEquals('Word.', $message3['lastmessage']);
2838         $this->assertEquals($messageid1, $message3['messageid']);
2839         $this->assertFalse($message3['isonline']);
2840         $this->assertFalse($message3['isread']);
2841         $this->assertFalse($message3['isblocked']);
2842         $this->assertEquals(2, $message3['unreadcount']);
2843     }
2845     /**
2846      * Tests retrieving conversations as another user without the proper capabilities.
2847      */
2848     public function test_messagearea_conversations_as_other_user_without_cap() {
2849         $this->resetAfterTest(true);
2851         // Create some users.
2852         $user1 = self::getDataGenerator()->create_user();
2853         $user2 = self::getDataGenerator()->create_user();
2855         // The person retrieving the conversations for another user.
2856         $this->setUser($user1);
2858         // Ensure an exception is thrown.
2859         $this->expectException('moodle_exception');
2860         core_message_external::data_for_messagearea_conversations($user2->id);
2861     }
2863     /**
2864      * Tests retrieving conversations with messaging disabled.
2865      */
2866     public function test_messagearea_conversations_messaging_disabled() {
2867         global $CFG;
2869         $this->resetAfterTest(true);
2871         // Create some skeleton data just so we can call the WS.
2872         $user = self::getDataGenerator()->create_user();
2874         // The person retrieving the conversations.
2875         $this->setUser($user);
2877         // Disable messaging.
2878         $CFG->messaging = 0;
2880         // Ensure an exception is thrown.
2881         $this->expectException('moodle_exception');
2882         core_message_external::data_for_messagearea_conversations($user->id);
2883     }
2885     /**
2886      * Tests retrieving contacts.
2887      */
2888     public function test_messagearea_contacts() {
2889         $this->resetAfterTest(true);
2891         // Create some users.
2892         $user1 = self::getDataGenerator()->create_user();
2894         // Set as the user.
2895         $this->setUser($user1);
2897         $user2 = new stdClass();
2898         $user2->firstname = 'User';
2899         $user2->lastname = 'A';
2900         $user2 = self::getDataGenerator()->create_user($user2);
2902         $user3 = new stdClass();
2903         $user3->firstname = 'User';
2904         $user3->lastname = 'B';
2905         $user3 = self::getDataGenerator()->create_user($user3);
2907         $user4 = new stdClass();
2908         $user4->firstname = 'User';
2909         $user4->lastname = 'C';
2910         $user4 = self::getDataGenerator()->create_user($user4);
2912         $user5 = new stdClass();
2913         $user5->firstname = 'User';
2914         $user5->lastname = 'D';
2915         $user5 = self::getDataGenerator()->create_user($user5);
2917         // Add some users as contacts.
2918         \core_message\api::add_contact($user1->id, $user2->id);
2919         \core_message\api::add_contact($user1->id, $user3->id);
2920         \core_message\api::add_contact($user1->id, $user4->id);
2922         // Retrieve the contacts.
2923         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2925         // We need to execute the return values cleaning process to simulate the web service server.
2926         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2927             $result);
2929         // Confirm the data is correct.
2930         $contacts = $result['contacts'];
2931         usort($contacts, ['static', 'sort_contacts']);
2932         $this->assertCount(3, $contacts);
2934         $contact1 = $contacts[0];
2935         $contact2 = $contacts[1];
2936         $contact3 = $contacts[2];
2938         $this->assertEquals($user2->id, $contact1['userid']);
2939         $this->assertFalse($contact1['ismessaging']);
2940         $this->assertFalse($contact1['sentfromcurrentuser']);
2941         $this->assertNull($contact1['lastmessage']);
2942         $this->assertNull($contact1['messageid']);
2943         $this->assertNull($contact1['isonline']);
2944         $this->assertFalse($contact1['isread']);
2945         $this->assertFalse($contact1['isblocked']);
2946         $this->assertNull($contact1['unreadcount']);
2948         $this->assertEquals($user3->id, $contact2['userid']);
2949         $this->assertFalse($contact2['ismessaging']);
2950         $this->assertFalse($contact2['sentfromcurrentuser']);
2951         $this->assertNull($contact2['lastmessage']);
2952         $this->assertNull($contact2['messageid']);
2953         $this->assertNull($contact2['isonline']);
2954         $this->assertFalse($contact2['isread']);
2955         $this->assertFalse($contact2['isblocked']);
2956         $this->assertNull($contact2['unreadcount']);
2958         $this->assertEquals($user4->id, $contact3['userid']);
2959         $this->assertFalse($contact3['ismessaging']);
2960         $this->assertFalse($contact3['sentfromcurrentuser']);
2961         $this->assertNull($contact3['lastmessage']);
2962         $this->assertNull($contact3['messageid']);
2963         $this->assertNull($contact3['isonline']);
2964         $this->assertFalse($contact3['isread']);
2965         $this->assertFalse($contact3['isblocked']);
2966         $this->assertNull($contact3['unreadcount']);
2967     }
2969     /**
2970      * Tests retrieving contacts as another user.
2971      */
2972     public function test_messagearea_contacts_as_other_user() {
2973         $this->resetAfterTest(true);
2975         $this->setAdminUser();
2977         // Create some users.
2978         $user1 = self::getDataGenerator()->create_user();
2980         $user2 = new stdClass();
2981         $user2->firstname = 'User';
2982         $user2->lastname = 'A';
2983         $user2 = self::getDataGenerator()->create_user($user2);
2985         $user3 = new stdClass();
2986         $user3->firstname = 'User';
2987         $user3->lastname = 'B';
2988         $user3 = self::getDataGenerator()->create_user($user3);
2990         $user4 = new stdClass();
2991         $user4->firstname = 'User';
2992         $user4->lastname = 'C';
2993         $user4 = self::getDataGenerator()->create_user($user4);
2995         $user5 = new stdClass();
2996         $user5->firstname = 'User';
2997         $user5->lastname = 'D';
2998         $user5 = self::getDataGenerator()->create_user($user5);
3000         // Add some users as contacts.
3001         \core_message\api::add_contact($user1->id, $user2->id);
3002         \core_message\api::add_contact($user1->id, $user3->id);
3003         \core_message\api::add_contact($user1->id, $user4->id);
3005         // Retrieve the contacts.
3006         $result = core_message_external::data_for_messagearea_contacts($user1->id);
3008         // We need to execute the return values cleaning process to simulate the web service server.
3009         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
3010             $result);
3012         // Confirm the data is correct.
3013         $contacts = $result['contacts'];
3014         usort($contacts, ['static', 'sort_contacts']);
3015         $this->assertCount(3, $contacts);
3017         $contact1 = $contacts[0];
3018         $contact2 = $contacts[1];
3019         $contact3 = $contacts[2];
3021         $this->assertEquals($user2->id, $contact1['userid']);
3022         $this->assertFalse($contact1['ismessaging']);
3023         $this->assertFalse($contact1['sentfromcurrentuser']);
3024         $this->assertNull($contact1['lastmessage']);
3025         $this->assertNull($contact1['messageid']);
3026         $this->assertFalse($contact1['isonline']);
3027         $this->assertFalse($contact1['isread']);
3028         $this->assertFalse($contact1['isblocked']);
3029         $this->assertNull($contact1['unreadcount']);
3031         $this->assertEquals($user3->id, $contact2['userid']);
3032         $this->assertFalse($contact2['ismessaging']);
3033         $this->assertFalse($contact2['sentfromcurrentuser']);
3034         $this->assertNull($contact2['lastmessage']);
3035         $this->assertNull($contact2['messageid']);
3036         $this->assertFalse($contact2['isonline']);
3037         $this->assertFalse($contact2['isread']);
3038         $this->assertFalse($contact2['isblocked']);
3039         $this->assertNull($contact2['unreadcount']);
3041         $this->assertEquals($user4->id, $contact3['userid']);
3042         $this->assertFalse($contact3['ismessaging']);
3043         $this->assertFalse($contact3['sentfromcurrentuser']);
3044         $this->assertNull($contact3['lastmessage']);
3045         $this->assertNull($contact3['messageid']);
3046         $this->assertFalse($contact3['isonline']);
3047         $this->assertFalse($contact3['isread']);
3048         $this->assertFalse($contact3['isblocked']);
3049         $this->assertNull($contact3['unreadcount']);
3050     }
3052     /**
3053      * Tests retrieving contacts as another user without the proper capabilities.
3054      */
3055     public function test_messagearea_contacts_as_other_user_without_cap() {
3056         $this->resetAfterTest(true);
3058         // Create some users.
3059         $user1 = self::getDataGenerator()->create_user();
3060         $user2 = self::getDataGenerator()->create_user();
3062         // The person retrieving the contacts for another user.
3063         $this->setUser($user1);
3065         // Perform the WS call and ensure an exception is thrown.
3066         $this->expectException('moodle_exception');
3067         core_message_external::data_for_messagearea_contacts($user2->id);
3068     }
3070     /**
3071      * Tests retrieving contacts with messaging disabled.
3072      */
3073     public function test_messagearea_contacts_messaging_disabled() {
3074         global $CFG;
3076         $this->resetAfterTest(true);
3078         // Create some skeleton data just so we can call the WS.
3079         $user = self::getDataGenerator()->create_user();
3081         // The person retrieving the contacts.
3082         $this->setUser($user);
3084         // Disable messaging.
3085         $CFG->messaging = 0;
3087         // Perform the WS call and ensure we are shown that it is disabled.
3088         $this->expectException('moodle_exception');
3089         core_message_external::data_for_messagearea_contacts($user->id);
3090     }
3092     /**
3093      * Tests retrieving messages.
3094      */
3095     public function test_messagearea_messages() {
3096         $this->resetAfterTest(true);
3098         // Create some users.
3099         $user1 = self::getDataGenerator()->create_user();
3100         $user2 = self::getDataGenerator()->create_user();
3102         // The person asking for the messages.
3103         $this->setUser($user1);
3105         // Send some messages back and forth.
3106         $time = time();
3107         $this->send_message($user1, $user2, 'Yo!', 0, $time);
3108         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3109         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3110         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3112         // Retrieve the messages.
3113         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
3114         $this->assertDebuggingCalledCount(3);
3116         // We need to execute the return values cleaning process to simulate the web service server.
3117         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
3118             $result);
3120         // Check the results are correct.
3121         $this->assertTrue($result['iscurrentuser']);
3122         $this->assertEquals($user1->id, $result['currentuserid']);
3123         $this->assertEquals($user2->id, $result['otheruserid']);
3124         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
3125         $this->assertNull($result['isonline']);
3127         // Confirm the message data is correct.
3128         $messages = $result['messages'];
3129         $this->assertCount(4, $messages);
3131         $message1 = $messages[0];
3132         $message2 = $messages[1];
3133         $message3 = $messages[2];
3134         $message4 = $messages[3];
3136         $this->assertEquals($user1->id, $message1['useridfrom']);
3137         $this->assertEquals($user2->id, $message1['useridto']);
3138         $this->assertTrue($message1['displayblocktime']);
3139         $this->assertContains('Yo!', $message1['text']);
3141         $this->assertEquals($user2->id, $message2['useridfrom']);
3142         $this->assertEquals($user1->id, $message2['useridto']);
3143         $this->assertFalse($message2['displayblocktime']);
3144         $this->assertContains('Sup mang?', $message2['text']);
3146         $this->assertEquals($user1->id, $message3['useridfrom']);
3147         $this->assertEquals($user2->id, $message3['useridto']);
3148         $this->assertFalse($message3['displayblocktime']);
3149         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
3151         $this->assertEquals($user2->id, $message4['useridfrom']);
3152         $this->assertEquals($user1->id, $message4['useridto']);
3153         $this->assertFalse($message4['displayblocktime']);
3154         $this->assertContains('Word.', $message4['text']);
3155     }
3157     /**
3158      * Tests retrieving messages.
3159      */
3160     public function test_messagearea_messages_timefrom() {
3161         $this->resetAfterTest(true);
3163         // Create some users.
3164         $user1 = self::getDataGenerator()->create_user();
3165         $user2 = self::getDataGenerator()->create_user();
3167         // The person asking for the messages.
3168         $this->setUser($user1);
3170         // Send some messages back and forth.
3171         $time = time();
3172         $this->send_message($user1, $user2, 'Message 1', 0, $time - 4);
3173         $this->send_message($user2, $user1, 'Message 2', 0, $time - 3);
3174         $this->send_message($user1, $user2, 'Message 3', 0, $time - 2);
3175         $this->send_message($user2, $user1, 'Message 4', 0, $time - 1);
3177         // Retrieve the messages from $time - 3, which should be the 3 most recent messages.
3178         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id, 0, 0, false, $time - 3);
3179         $this->assertDebuggingCalledCount(3);
3181         // We need to execute the return values cleaning process to simulate the web service server.
3182         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
3183             $result);
3185         // Confirm the message data is correct. We shouldn't get 'Message 1' back.
3186         $messages = $result['messages'];
3187         $this->assertCount(3, $messages);
3189         $message1 = $messages[0];
3190         $message2 = $messages[1];
3191         $message3 = $messages[2];
3193         $this->assertContains('Message 2', $message1['text']);
3194         $this->assertContains('Message 3', $message2['text']);
3195         $this->assertContains('Message 4', $message3['text']);
3196     }
3198     /**
3199      * Tests retrieving messages as another user.
3200      */
3201     public function test_messagearea_messages_as_other_user() {
3202         $this->resetAfterTest(true);
3204         // Set as admin.
3205         $this->setAdminUser();
3207         // Create some users.
3208         $user1 = self::getDataGenerator()->create_user();
3209         $user2 = self::getDataGenerator()->create_user();
3211         // Send some messages back and forth.
3212         $time = time();
3213         $this->send_message($user1, $user2, 'Yo!', 0, $time);
3214         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3215         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3216         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3218         // Retrieve the messages.
3219         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
3220         $this->assertDebuggingCalledCount(3);
3222         // We need to execute the return values cleaning process to simulate the web service server.
3223         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
3224             $result);
3226         // Check the results are correct.
3227         $this->assertFalse($result['iscurrentuser']);
3228         $this->assertEquals($user1->id, $result['currentuserid']);
3229         $this->assertEquals($user2->id, $result['otheruserid']);
3230         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
3231         $this->assertFalse($result['isonline']);
3233         // Confirm the message data is correct.
3234         $messages = $result['messages'];
3235         $this->assertCount(4, $messages);
3237         $message1 = $messages[0];
3238         $message2 = $messages[1];
3239         $message3 = $messages[2];
3240         $message4 = $messages[3];
3242         $this->assertEquals($user1->id, $message1['useridfrom']);
3243         $this->assertEquals($user2->id, $message1['useridto']);
3244         $this->assertTrue($message1['displayblocktime']);
3245         $this->assertContains('Yo!', $message1['text']);
3247         $this->assertEquals($user2->id, $message2['useridfrom']);
3248         $this->assertEquals($user1->id, $message2['useridto']);
3249         $this->assertFalse($message2['displayblocktime']);
3250         $this->assertContains('Sup mang?', $message2['text']);
3252         $this->assertEquals($user1->id, $message3['useridfrom']);
3253         $this->assertEquals($user2->id, $message3['useridto']);
3254         $this->assertFalse($message3['displayblocktime']);
3255         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
3257         $this->assertEquals($user2->id, $message4['useridfrom']);
3258         $this->assertEquals($user1->id, $message4['useridto']);
3259         $this->assertFalse($message4['displayblocktime']);
3260         $this->assertContains('Word.', $message4['text']);
3261     }
3263     /**
3264      * Tests retrieving messages as another user without the proper capabilities.
3265      */
3266     public function test_messagearea_messages_as_other_user_without_cap() {
3267         $this->resetAfterTest(true);
3269         // Create some users.
3270         $user1 = self::getDataGenerator()->create_user();
3271         $user2 = self::getDataGenerator()->create_user();
3272         $user3 = self::getDataGenerator()->create_user();
3274         // The person asking for the messages for another user.
3275         $this->setUser($user1);
3277         // Ensure an exception is thrown.
3278         $this->expectException('moodle_exception');
3279         core_message_external::data_for_messagearea_messages($user2->id, $user3->id);
3280     }
3282     /**
3283      * Tests retrieving messages with messaging disabled.
3284      */
3285     public function test_messagearea_messages_messaging_disabled() {
3286         global $CFG;
3288         $this->resetAfterTest(true);
3290         // Create some skeleton data just so we can call the WS.
3291         $user1 = self::getDataGenerator()->create_user();
3292         $user2 = self::getDataGenerator()->create_user();
3294         // The person asking for the messages for another user.
3295         $this->setUser($user1);
3297         // Disable messaging.
3298         $CFG->messaging = 0;
3300         // Ensure an exception is thrown.
3301         $this->expectException('moodle_exception');
3302         core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
3303     }
3305     /**
3306      * Tests get_conversation_messages for retrieving messages.
3307      */
3308     public function test_get_conversation_messages() {
3309         $this->resetAfterTest(true);
3311         // Create some users.
3312         $user1 = self::getDataGenerator()->create_user();
3313         $user2 = self::getDataGenerator()->create_user();
3314         $user3 = self::getDataGenerator()->create_user();
3315         $user4 = self::getDataGenerator()->create_user();
3316         $user5 = self::getDataGenerator()->create_user();
3318         // Create group conversation.
3319         $conversation = \core_message\api::create_conversation(
3320             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3321             [$user1->id, $user2->id, $user3->id, $user4->id]
3322         );
3324         // The person asking for the messages.
3325         $this->setUser($user1);
3327         // Send some messages back and forth.
3328         $time = time();
3329         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time);
3330         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Sup mang?', $time + 1);
3331         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Writing PHPUnit tests!', $time + 2);
3332         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 3);
3334         // Retrieve the messages.
3335         $result = core_message_external::get_conversation_messages($user1->id, $conversation->id);
3337         // We need to execute the return values cleaning process to simulate the web service server.
3338         $result = external_api::clean_returnvalue(core_message_external::get_conversation_messages_returns(),
3339             $result);
3341         // Check the results are correct.
3342         $this->assertEquals($conversation->id, $result['id']);
3344         // Confirm the members data is correct.
3345         $members = $result['members'];
3346         $this->assertCount(3, $members);
3347         $membersid = [$members[0]['id'], $members[1]['id'], $members[2]['id']];
3348         $this->assertContains($user1->id, $membersid);
3349         $this->assertContains($user2->id, $membersid);
3350         $this->assertContains($user3->id, $membersid);
3352         $membersfullnames = [$members[0]['fullname'], $members[1]['fullname'], $members[2]['fullname']];
3353         $this->assertContains(fullname($user1), $membersfullnames);
3354         $this->assertContains(fullname($user2), $membersfullnames);
3355         $this->assertContains(fullname($user3), $membersfullnames);
3357         // Confirm the messages data is correct.
3358         $messages = $result['messages'];
3359         $this->assertCount(4, $messages);
3361         $message1 = $messages[0];
3362         $message2 = $messages[1];
3363         $message3 = $messages[2];
3364         $message4 = $messages[3];
3366         $this->assertEquals($user1->id, $message1['useridfrom']);
3367         $this->assertContains('Yo!', $message1['text']);
3369         $this->assertEquals($user3->id, $message2['useridfrom']);
3370         $this->assertContains('Sup mang?', $message2['text']);
3372         $this->assertEquals($user2->id, $message3['useridfrom']);
3373         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
3375         $this->assertEquals($user1->id, $message4['useridfrom']);
3376         $this->assertContains('Word.', $message4['text']);
3377     }
3379     /**
3380      * Tests get_conversation_messages for retrieving messages using timefrom parameter.
3381      */
3382     public function test_get_conversation_messages_timefrom() {
3383         $this->resetAfterTest(true);
3385         // Create some users.
3386         $user1 = self::getDataGenerator()->create_user();
3387         $user2 = self::getDataGenerator()->create_user();
3388         $user3 = self::getDataGenerator()->create_user();
3389         $user4 = self::getDataGenerator()->create_user();
3391         // Create group conversation.
3392         $conversation = \core_message\api::create_conversation(
3393             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3394             [$user1->id, $user2->id, $user3->id]