f78cc46b346eff8a4508b5cac312b81a7fc5c934
[moodle.git] / message / tests / externallib_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * External message functions unit tests
19  *
20  * @package    core_message
21  * @category   external
22  * @copyright  2012 Jerome Mouneyrac
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
30 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
31 require_once($CFG->dirroot . '/message/externallib.php');
33 class core_message_externallib_testcase extends externallib_advanced_testcase {
35     /**
36      * Tests set up
37      */
38     protected function setUp() {
39         global $CFG;
41         require_once($CFG->dirroot . '/message/lib.php');
42     }
44     /**
45      * Send a fake message.
46      *
47      * {@link message_send()} does not support transaction, this function will simulate a message
48      * sent from a user to another. We should stop using it once {@link message_send()} will support
49      * transactions. This is not clean at all, this is just used to add rows to the table.
50      *
51      * @param stdClass $userfrom user object of the one sending the message.
52      * @param stdClass $userto user object of the one receiving the message.
53      * @param string $message message to send.
54      * @param int $notification is the message a notification.
55      * @param int $time the time the message was sent
56      */
57     protected function send_message($userfrom, $userto, $message = 'Hello world!', $notification = 0, $time = 0) {
58         global $DB;
60         if (empty($time)) {
61             $time = time();
62         }
64         if ($notification) {
65             $record = new stdClass();
66             $record->useridfrom = $userfrom->id;
67             $record->useridto = $userto->id;
68             $record->subject = 'No subject';
69             $record->fullmessage = $message;
70             $record->smallmessage = $message;
71             $record->timecreated = $time;
73             return $DB->insert_record('notifications', $record);
74         }
76         if (!$conversationid = \core_message\api::get_conversation_between_users([$userfrom->id, $userto->id])) {
77             $conversationid = \core_message\api::create_conversation_between_users([$userfrom->id,
78                 $userto->id]);
79         }
81         // Ok, send the message.
82         $record = new stdClass();
83         $record->useridfrom = $userfrom->id;
84         $record->conversationid = $conversationid;
85         $record->subject = 'No subject';
86         $record->fullmessage = $message;
87         $record->smallmessage = $message;
88         $record->timecreated = $time;
90         return $DB->insert_record('messages', $record);
91     }
93     /**
94      * Test send_instant_messages
95      */
96     public function test_send_instant_messages() {
98         global $DB, $USER, $CFG;
100         $this->resetAfterTest(true);
101         // Transactions used in tests, tell phpunit use alternative reset method.
102         $this->preventResetByRollback();
104         // Turn off all message processors (so nothing is really sent)
105         require_once($CFG->dirroot . '/message/lib.php');
106         $messageprocessors = get_message_processors();
107         foreach($messageprocessors as $messageprocessor) {
108             $messageprocessor->enabled = 0;
109             $DB->update_record('message_processors', $messageprocessor);
110         }
112         // Set the required capabilities by the external function
113         $contextid = context_system::instance()->id;
114         $roleid = $this->assignUserCapability('moodle/site:sendmessage', $contextid);
116         $user1 = self::getDataGenerator()->create_user();
118         // Create test message data.
119         $message1 = array();
120         $message1['touserid'] = $user1->id;
121         $message1['text'] = 'the message.';
122         $message1['clientmsgid'] = 4;
123         $messages = array($message1);
125         $sentmessages = core_message_external::send_instant_messages($messages);
127         // We need to execute the return values cleaning process to simulate the web service server.
128         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
130         $sql = "SELECT m.*, mcm.userid as useridto
131                  FROM {messages} m
132            INNER JOIN {message_conversations} mc
133                    ON m.conversationid = mc.id
134            INNER JOIN {message_conversation_members} mcm
135                    ON mcm.conversationid = mc.id
136                 WHERE mcm.userid != ?
137                   AND m.id = ?";
138         $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessages[0]['msgid']]);
140         // Confirm that the message was inserted correctly.
141         $this->assertEquals($themessage->useridfrom, $USER->id);
142         $this->assertEquals($themessage->useridto, $message1['touserid']);
143         $this->assertEquals($themessage->smallmessage, $message1['text']);
144         $this->assertEquals($sentmessages[0]['clientmsgid'], $message1['clientmsgid']);
145     }
147     /**
148      * Test create_contacts.
149      */
150     public function test_create_contacts() {
151         $this->resetAfterTest(true);
153         $user1 = self::getDataGenerator()->create_user();
154         $user2 = self::getDataGenerator()->create_user();
155         $user3 = self::getDataGenerator()->create_user();
156         $user4 = self::getDataGenerator()->create_user();
157         $user5 = self::getDataGenerator()->create_user();
158         $this->setUser($user1);
160         // Adding a contact.
161         $return = core_message_external::create_contacts(array($user2->id));
162         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
163         $this->assertEquals(array(), $return);
165         // Adding a contact who is already a contact.
166         $return = core_message_external::create_contacts(array($user2->id));
167         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
168         $this->assertEquals(array(), $return);
170         // Adding multiple contacts.
171         $return = core_message_external::create_contacts(array($user3->id, $user4->id));
172         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
173         $this->assertEquals(array(), $return);
175         // Adding a non-existing user.
176         $return = core_message_external::create_contacts(array(99999));
177         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
178         $this->assertCount(1, $return);
179         $return = array_pop($return);
180         $this->assertEquals($return['warningcode'], 'contactnotcreated');
181         $this->assertEquals($return['itemid'], 99999);
183         // Adding contacts with valid and invalid parameters.
184         $return = core_message_external::create_contacts(array($user5->id, 99999));
185         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
186         $this->assertCount(1, $return);
187         $return = array_pop($return);
188         $this->assertEquals($return['warningcode'], 'contactnotcreated');
189         $this->assertEquals($return['itemid'], 99999);
191         // Try to add a contact to another user, should throw an exception.
192         // All assertions must be added before this point.
193         $this->expectException('required_capability_exception');
194         core_message_external::create_contacts(array($user2->id), $user3->id);
195     }
197     /**
198      * Test delete_contacts.
199      */
200     public function test_delete_contacts() {
201         $this->resetAfterTest(true);
203         $user1 = self::getDataGenerator()->create_user();
204         $user2 = self::getDataGenerator()->create_user();
205         $user3 = self::getDataGenerator()->create_user();
206         $user4 = self::getDataGenerator()->create_user();
207         $user5 = self::getDataGenerator()->create_user();
208         $user6 = self::getDataGenerator()->create_user();
209         $this->setUser($user1);
210         $this->assertEquals(array(), core_message_external::create_contacts(
211             array($user3->id, $user4->id, $user5->id, $user6->id)));
213         // Removing a non-contact.
214         $return = core_message_external::delete_contacts(array($user2->id));
215         $this->assertNull($return);
217         // Removing one contact.
218         $return = core_message_external::delete_contacts(array($user3->id));
219         $this->assertNull($return);
221         // Removing multiple contacts.
222         $return = core_message_external::delete_contacts(array($user4->id, $user5->id));
223         $this->assertNull($return);
225         // Removing contact from unexisting user.
226         $return = core_message_external::delete_contacts(array(99999));
227         $this->assertNull($return);
229         // Removing mixed valid and invalid data.
230         $return = core_message_external::delete_contacts(array($user6->id, 99999));
231         $this->assertNull($return);
233         // Try to delete a contact of another user contact list, should throw an exception.
234         // All assertions must be added before this point.
235         $this->expectException('required_capability_exception');
236         core_message_external::delete_contacts(array($user2->id), $user3->id);
237     }
239     /**
240      * Test block_contacts.
241      */
242     public function test_block_contacts() {
243         $this->resetAfterTest(true);
245         $user1 = self::getDataGenerator()->create_user();
246         $user2 = self::getDataGenerator()->create_user();
247         $user3 = self::getDataGenerator()->create_user();
248         $user4 = self::getDataGenerator()->create_user();
249         $user5 = self::getDataGenerator()->create_user();
250         $this->setUser($user1);
251         $this->assertEquals(array(), core_message_external::create_contacts(array($user3->id, $user4->id, $user5->id)));
253         // Blocking a contact.
254         $return = core_message_external::block_contacts(array($user2->id));
255         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
256         $this->assertEquals(array(), $return);
258         // Blocking a contact who is already a contact.
259         $return = core_message_external::block_contacts(array($user2->id));
260         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
261         $this->assertEquals(array(), $return);
263         // Blocking multiple contacts.
264         $return = core_message_external::block_contacts(array($user3->id, $user4->id));
265         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
266         $this->assertEquals(array(), $return);
268         // Blocking a non-existing user.
269         $return = core_message_external::block_contacts(array(99999));
270         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
271         $this->assertCount(1, $return);
272         $return = array_pop($return);
273         $this->assertEquals($return['warningcode'], 'contactnotblocked');
274         $this->assertEquals($return['itemid'], 99999);
276         // Blocking contacts with valid and invalid parameters.
277         $return = core_message_external::block_contacts(array($user5->id, 99999));
278         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
279         $this->assertCount(1, $return);
280         $return = array_pop($return);
281         $this->assertEquals($return['warningcode'], 'contactnotblocked');
282         $this->assertEquals($return['itemid'], 99999);
284         // Try to block a contact of another user contact list, should throw an exception.
285         // All assertions must be added before this point.
286         $this->expectException('required_capability_exception');
287         core_message_external::block_contacts(array($user2->id), $user3->id);
288     }
290     /**
291      * Test unblock_contacts.
292      */
293     public function test_unblock_contacts() {
294         $this->resetAfterTest(true);
296         $user1 = self::getDataGenerator()->create_user();
297         $user2 = self::getDataGenerator()->create_user();
298         $user3 = self::getDataGenerator()->create_user();
299         $user4 = self::getDataGenerator()->create_user();
300         $user5 = self::getDataGenerator()->create_user();
301         $user6 = self::getDataGenerator()->create_user();
302         $this->setUser($user1);
303         $this->assertEquals(array(), core_message_external::create_contacts(
304             array($user3->id, $user4->id, $user5->id, $user6->id)));
306         // Removing a non-contact.
307         $return = core_message_external::unblock_contacts(array($user2->id));
308         $this->assertNull($return);
310         // Removing one contact.
311         $return = core_message_external::unblock_contacts(array($user3->id));
312         $this->assertNull($return);
314         // Removing multiple contacts.
315         $return = core_message_external::unblock_contacts(array($user4->id, $user5->id));
316         $this->assertNull($return);
318         // Removing contact from unexisting user.
319         $return = core_message_external::unblock_contacts(array(99999));
320         $this->assertNull($return);
322         // Removing mixed valid and invalid data.
323         $return = core_message_external::unblock_contacts(array($user6->id, 99999));
324         $this->assertNull($return);
326         // Try to unblock a contact of another user contact list, should throw an exception.
327         // All assertions must be added before this point.
328         $this->expectException('required_capability_exception');
329         core_message_external::unblock_contacts(array($user2->id), $user3->id);
330     }
332     /**
333      * Test get_contacts.
334      */
335     public function test_get_contacts() {
336         $this->resetAfterTest(true);
338         $user1 = self::getDataGenerator()->create_user();
339         $user_stranger = self::getDataGenerator()->create_user();
340         $user_offline1 = self::getDataGenerator()->create_user();
341         $user_offline2 = self::getDataGenerator()->create_user();
342         $user_offline3 = self::getDataGenerator()->create_user();
343         $user_online = new stdClass();
344         $user_online->lastaccess = time();
345         $user_online = self::getDataGenerator()->create_user($user_online);
346         $user_blocked = self::getDataGenerator()->create_user();
347         $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
349         // Login as user1.
350         $this->setUser($user1);
351         $this->assertEquals(array(), core_message_external::create_contacts(
352             array($user_offline1->id, $user_offline2->id, $user_offline3->id, $user_online->id)));
354         // User_stranger sends a couple of messages to user1.
355         $this->send_message($user_stranger, $user1, 'Hello there!');
356         $this->send_message($user_stranger, $user1, 'How you goin?');
357         $this->send_message($user_stranger, $user1, 'Cya!');
358         $this->send_message($noreplyuser, $user1, 'I am not a real user');
360         // User_blocked sends a message to user1.
361         $this->send_message($user_blocked, $user1, 'Here, have some spam.');
363         // Retrieve the contacts of the user.
364         $this->setUser($user1);
365         $contacts = core_message_external::get_contacts();
366         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
367         $this->assertCount(3, $contacts['offline']);
368         $this->assertCount(1, $contacts['online']);
369         $this->assertCount(3, $contacts['strangers']);
370         core_message_external::block_contacts(array($user_blocked->id));
371         $contacts = core_message_external::get_contacts();
372         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
373         $this->assertCount(3, $contacts['offline']);
374         $this->assertCount(1, $contacts['online']);
375         $this->assertCount(2, $contacts['strangers']);
377         // Checking some of the fields returned.
378         $stranger = array_pop($contacts['strangers']);
380         $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
381         $this->assertEquals(1, $stranger['unread']);
383         // Check that deleted users are not returned.
384         delete_user($user_offline1);
385         delete_user($user_stranger);
386         delete_user($user_online);
387         $contacts = core_message_external::get_contacts();
388         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
389         $this->assertCount(2, $contacts['offline']);
390         $this->assertCount(0, $contacts['online']);
391         $this->assertCount(1, $contacts['strangers']);
392     }
394     /**
395      * Test search_contacts.
396      * @expectedException moodle_exception
397      */
398     public function test_search_contacts() {
399         global $DB;
400         $this->resetAfterTest(true);
402         $course1 = $this->getDataGenerator()->create_course();
403         $course2 = $this->getDataGenerator()->create_course();
405         $user1 = new stdClass();
406         $user1->firstname = 'X';
407         $user1->lastname = 'X';
408         $user1 = $this->getDataGenerator()->create_user($user1);
409         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
410         $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
412         $user2 = new stdClass();
413         $user2->firstname = 'Eric';
414         $user2->lastname = 'Cartman';
415         $user2 = self::getDataGenerator()->create_user($user2);
416         $user3 = new stdClass();
417         $user3->firstname = 'Stan';
418         $user3->lastname = 'Marsh';
419         $user3 = self::getDataGenerator()->create_user($user3);
420         self::getDataGenerator()->enrol_user($user3->id, $course1->id);
421         $user4 = new stdClass();
422         $user4->firstname = 'Kyle';
423         $user4->lastname = 'Broflovski';
424         $user4 = self::getDataGenerator()->create_user($user4);
425         $user5 = new stdClass();
426         $user5->firstname = 'Kenny';
427         $user5->lastname = 'McCormick';
428         $user5 = self::getDataGenerator()->create_user($user5);
429         self::getDataGenerator()->enrol_user($user5->id, $course2->id);
431         $this->setUser($user1);
433         $results = core_message_external::search_contacts('r');
434         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
435         $this->assertCount(5, $results); // Users 2 through 5 + admin
437         $results = core_message_external::search_contacts('r', true);
438         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
439         $this->assertCount(2, $results);
441         $results = core_message_external::search_contacts('Kyle', false);
442         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
443         $this->assertCount(1, $results);
444         $result = reset($results);
445         $this->assertEquals($user4->id, $result['id']);
447         $results = core_message_external::search_contacts('y', false);
448         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
449         $this->assertCount(2, $results);
451         $results = core_message_external::search_contacts('y', true);
452         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
453         $this->assertCount(1, $results);
454         $result = reset($results);
455         $this->assertEquals($user5->id, $result['id']);
457         // Empty query, will throw an exception.
458         $results = core_message_external::search_contacts('');
459     }
461     /**
462      * Test get_messages.
463      */
464     public function test_get_messages() {
465         global $CFG, $DB;
466         $this->resetAfterTest(true);
468         $this->preventResetByRollback();
469         // This mark the messages as read!.
470         $sink = $this->redirectMessages();
472         $user1 = self::getDataGenerator()->create_user();
473         $user2 = self::getDataGenerator()->create_user();
474         $user3 = self::getDataGenerator()->create_user();
476         $course = self::getDataGenerator()->create_course();
478         // Send a message from one user to another.
479         message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
480         message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
481         message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
482         message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
483         message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);
485         $this->setUser($user1);
486         // Get read conversations from user1 to user2.
487         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
488         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
489         $this->assertCount(1, $messages['messages']);
491         // Delete the message.
492         $message = array_shift($messages['messages']);
493         \core_message\api::delete_message($user1->id, $message['id']);
495         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
496         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
497         $this->assertCount(0, $messages['messages']);
499         // Get unread conversations from user1 to user2.
500         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
501         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
502         $this->assertCount(0, $messages['messages']);
504         // Get read messages send from user1.
505         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
506         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
507         $this->assertCount(1, $messages['messages']);
509         $this->setUser($user2);
510         // Get read conversations from any user to user2.
511         $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
512         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
513         $this->assertCount(2, $messages['messages']);
515         // Conversations from user3 to user2.
516         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
517         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
518         $this->assertCount(1, $messages['messages']);
520         // Delete the message.
521         $message = array_shift($messages['messages']);
522         \core_message\api::delete_message($user2->id, $message['id']);
524         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
525         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
526         $this->assertCount(0, $messages['messages']);
528         $this->setUser($user3);
529         // Get read notifications received by user3.
530         $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
531         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
532         $this->assertCount(0, $messages['messages']);
534         // Now, create some notifications...
535         // We are creating fake notifications but based on real ones.
537         // This one comes from a disabled plugin's provider and therefore is not sent.
538         $eventdata = new \core\message\message();
539         $eventdata->courseid          = $course->id;
540         $eventdata->notification      = 1;
541         $eventdata->modulename        = 'moodle';
542         $eventdata->component         = 'enrol_paypal';
543         $eventdata->name              = 'paypal_enrolment';
544         $eventdata->userfrom          = get_admin();
545         $eventdata->userto            = $user1;
546         $eventdata->subject           = "Moodle: PayPal payment";
547         $eventdata->fullmessage       = "Your PayPal payment is pending.";
548         $eventdata->fullmessageformat = FORMAT_PLAIN;
549         $eventdata->fullmessagehtml   = '';
550         $eventdata->smallmessage      = '';
551         message_send($eventdata);
552         $this->assertDebuggingCalled('Attempt to send msg from a provider enrol_paypal/paypal_enrolment '.
553             'that is inactive or not allowed for the user id='.$user1->id);
555         // This one omits notification = 1.
556         $message = new \core\message\message();
557         $message->courseid          = $course->id;
558         $message->component         = 'enrol_manual';
559         $message->name              = 'expiry_notification';
560         $message->userfrom          = $user2;
561         $message->userto            = $user1;
562         $message->subject           = 'Test: This is not a notification but otherwise is valid';
563         $message->fullmessage       = 'Test: Full message';
564         $message->fullmessageformat = FORMAT_MARKDOWN;
565         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
566         $message->smallmessage      = $message->subject;
567         $message->contexturlname    = $course->fullname;
568         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
569         message_send($message);
571         $message = new \core\message\message();
572         $message->courseid          = $course->id;
573         $message->notification      = 1;
574         $message->component         = 'enrol_manual';
575         $message->name              = 'expiry_notification';
576         $message->userfrom          = $user2;
577         $message->userto            = $user1;
578         $message->subject           = 'Enrolment expired';
579         $message->fullmessage       = 'Enrolment expired blah blah blah';
580         $message->fullmessageformat = FORMAT_MARKDOWN;
581         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
582         $message->smallmessage      = $message->subject;
583         $message->contexturlname    = $course->fullname;
584         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
585         message_send($message);
587         $userfrom = core_user::get_noreply_user();
588         $userfrom->maildisplay = true;
589         $eventdata = new \core\message\message();
590         $eventdata->courseid          = $course->id;
591         $eventdata->component         = 'moodle';
592         $eventdata->name              = 'badgecreatornotice';
593         $eventdata->userfrom          = $userfrom;
594         $eventdata->userto            = $user1;
595         $eventdata->notification      = 1;
596         $eventdata->subject           = 'New badge';
597         $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
598         $eventdata->fullmessageformat = FORMAT_PLAIN;
599         $eventdata->fullmessagehtml   = $eventdata->subject;
600         $eventdata->smallmessage      = $eventdata->subject;
601         message_send($eventdata);
603         $eventdata = new \core\message\message();
604         $eventdata->courseid         = $course->id;
605         $eventdata->name             = 'submission';
606         $eventdata->component        = 'mod_feedback';
607         $eventdata->userfrom         = $user1;
608         $eventdata->userto           = $user2;
609         $eventdata->subject          = 'Feedback submitted';
610         $eventdata->fullmessage      = 'Feedback submitted from an user';
611         $eventdata->fullmessageformat = FORMAT_PLAIN;
612         $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
613         $eventdata->smallmessage     = '';
614         message_send($eventdata);
616         $this->setUser($user1);
617         // Get read notifications from any user to user1.
618         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
619         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
620         $this->assertCount(3, $messages['messages']);
622         // Get one read notifications from any user to user1.
623         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
624         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
625         $this->assertCount(1, $messages['messages']);
627         // Get unread notifications from any user to user1.
628         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
629         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
630         $this->assertCount(0, $messages['messages']);
632         // Get read both type of messages from any user to user1.
633         $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
634         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
635         $this->assertCount(4, $messages['messages']);
637         // Get read notifications from no-reply-user to user1.
638         $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
639         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
640         $this->assertCount(1, $messages['messages']);
642         // Get notifications send by user1 to any user.
643         $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
644         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
645         $this->assertCount(1, $messages['messages']);
647         // Test warnings.
648         $CFG->messaging = 0;
650         $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
651         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
652         $this->assertCount(1, $messages['warnings']);
654         // Test exceptions.
656         // Messaging disabled.
657         try {
658             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
659             $this->fail('Exception expected due messaging disabled.');
660         } catch (moodle_exception $e) {
661             $this->assertEquals('disabled', $e->errorcode);
662         }
664         $CFG->messaging = 1;
666         // Invalid users.
667         try {
668             $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
669             $this->fail('Exception expected due invalid users.');
670         } catch (moodle_exception $e) {
671             $this->assertEquals('accessdenied', $e->errorcode);
672         }
674         // Invalid user ids.
675         try {
676             $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
677             $this->fail('Exception expected due invalid users.');
678         } catch (moodle_exception $e) {
679             $this->assertEquals('invaliduser', $e->errorcode);
680         }
682         // Invalid users (permissions).
683         $this->setUser($user2);
684         try {
685             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
686             $this->fail('Exception expected due invalid user.');
687         } catch (moodle_exception $e) {
688             $this->assertEquals('accessdenied', $e->errorcode);
689         }
691     }
693     /**
694      * Test get_messages where we want all messages from a user, sent to any user.
695      */
696     public function test_get_messages_useridto_all() {
697         $this->resetAfterTest(true);
699         $user1 = self::getDataGenerator()->create_user();
700         $user2 = self::getDataGenerator()->create_user();
701         $user3 = self::getDataGenerator()->create_user();
703         $this->setUser($user1);
705         // Send a message from user 1 to two other users.
706         $this->send_message($user1, $user2, 'some random text 1', 0, 1);
707         $this->send_message($user1, $user3, 'some random text 2', 0, 2);
709         // Get messages sent from user 1.
710         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', false, false, 0, 0);
711         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
713         // Confirm the data is correct.
714         $messages = $messages['messages'];
715         $this->assertCount(2, $messages);
717         $message1 = array_shift($messages);
718         $message2 = array_shift($messages);
720         $this->assertEquals($user1->id, $message1['useridfrom']);
721         $this->assertEquals($user2->id, $message1['useridto']);
723         $this->assertEquals($user1->id, $message2['useridfrom']);
724         $this->assertEquals($user3->id, $message2['useridto']);
725     }
727     /**
728      * Test get_messages where we want all messages to a user, sent by any user.
729      */
730     public function test_get_messages_useridfrom_all() {
731         $this->resetAfterTest();
733         $user1 = self::getDataGenerator()->create_user();
734         $user2 = self::getDataGenerator()->create_user();
735         $user3 = self::getDataGenerator()->create_user();
737         $this->setUser($user1);
739         // Send a message to user 1 from two other users.
740         $this->send_message($user2, $user1, 'some random text 1', 0, 1);
741         $this->send_message($user3, $user1, 'some random text 2', 0, 2);
743         // Get messages sent to user 1.
744         $messages = core_message_external::get_messages($user1->id, 0, 'conversations', false, false, 0, 0);
745         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
747         // Confirm the data is correct.
748         $messages = $messages['messages'];
749         $this->assertCount(2, $messages);
751         $message1 = array_shift($messages);
752         $message2 = array_shift($messages);
754         $this->assertEquals($user2->id, $message1['useridfrom']);
755         $this->assertEquals($user1->id, $message1['useridto']);
757         $this->assertEquals($user3->id, $message2['useridfrom']);
758         $this->assertEquals($user1->id, $message2['useridto']);
759     }
761     /**
762      * Test get_blocked_users.
763      */
764     public function test_get_blocked_users() {
765         $this->resetAfterTest(true);
767         $user1 = self::getDataGenerator()->create_user();
768         $userstranger = self::getDataGenerator()->create_user();
769         $useroffline1 = self::getDataGenerator()->create_user();
770         $useroffline2 = self::getDataGenerator()->create_user();
771         $userblocked = self::getDataGenerator()->create_user();
773         // Login as user1.
774         $this->setUser($user1);
775         $this->assertEquals(array(), core_message_external::create_contacts(
776             array($useroffline1->id, $useroffline2->id)));
778         // The userstranger sends a couple of messages to user1.
779         $this->send_message($userstranger, $user1, 'Hello there!');
780         $this->send_message($userstranger, $user1, 'How you goin?');
782         // The userblocked sends a message to user1.
783         // Note that this user is not blocked at this point.
784         $this->send_message($userblocked, $user1, 'Here, have some spam.');
786         // Retrieve the list of blocked users.
787         $this->setUser($user1);
788         $blockedusers = core_message_external::get_blocked_users($user1->id);
789         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
790         $this->assertCount(0, $blockedusers['users']);
792         // Block the $userblocked and retrieve again the list.
793         core_message_external::block_contacts(array($userblocked->id));
794         $blockedusers = core_message_external::get_blocked_users($user1->id);
795         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
796         $this->assertCount(1, $blockedusers['users']);
798         // Remove the $userblocked and check that the list now is empty.
799         delete_user($userblocked);
800         $blockedusers = core_message_external::get_blocked_users($user1->id);
801         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
802         $this->assertCount(0, $blockedusers['users']);
804     }
806     /**
807      * Test mark_message_read.
808      */
809     public function test_mark_message_read() {
810         $this->resetAfterTest(true);
812         $user1 = self::getDataGenerator()->create_user();
813         $user2 = self::getDataGenerator()->create_user();
814         $user3 = self::getDataGenerator()->create_user();
816         // Login as user1.
817         $this->setUser($user1);
818         $this->assertEquals(array(), core_message_external::create_contacts(
819             array($user2->id, $user3->id)));
821         // The user2 sends a couple of messages to user1.
822         $this->send_message($user2, $user1, 'Hello there!');
823         $this->send_message($user2, $user1, 'How you goin?');
824         $this->send_message($user3, $user1, 'How you goin?');
825         $this->send_message($user3, $user2, 'How you goin?');
827         // Retrieve all messages sent by user2 (they are currently unread).
828         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
830         $messageids = array();
831         foreach ($lastmessages as $m) {
832             $messageid = core_message_external::mark_message_read($m->id, time());
833             $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
834         }
836         // Retrieve all messages sent (they are currently read).
837         $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
838         $this->assertCount(2, $lastmessages);
839         $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
840         $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
842         // Retrieve all messages sent by any user (that are currently unread).
843         $lastmessages = message_get_messages($user1->id, 0, 0, false);
844         $this->assertCount(1, $lastmessages);
846         // Invalid message ids.
847         try {
848             $messageid = core_message_external::mark_message_read(1337, time());
849             $this->fail('Exception expected due invalid messageid.');
850         } catch (dml_missing_record_exception $e) {
851             $this->assertEquals('invalidrecordunknown', $e->errorcode);
852         }
854         // A message to a different user.
855         $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
856         $messageid = array_pop($lastmessages)->id;
857         try {
858             $messageid = core_message_external::mark_message_read($messageid, time());
859             $this->fail('Exception expected due invalid messageid.');
860         } catch (invalid_parameter_exception $e) {
861             $this->assertEquals('invalidparameter', $e->errorcode);
862         }
863     }
865     /**
866      * Test mark_notification_read.
867      */
868     public function test_mark_notification_read() {
869         $this->resetAfterTest(true);
871         $user1 = self::getDataGenerator()->create_user();
872         $user2 = self::getDataGenerator()->create_user();
873         $user3 = self::getDataGenerator()->create_user();
875         // Login as user1.
876         $this->setUser($user1);
877         $this->assertEquals(array(), core_message_external::create_contacts(
878             array($user2->id, $user3->id)));
880         // The user2 sends a couple of notifications to user1.
881         $this->send_message($user2, $user1, 'Hello there!', 1);
882         $this->send_message($user2, $user1, 'How you goin?', 1);
883         $this->send_message($user3, $user1, 'How you goin?', 1);
884         $this->send_message($user3, $user2, 'How you goin?', 1);
886         // Retrieve all notifications sent by user2 (they are currently unread).
887         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, false);
889         $notificationids = array();
890         foreach ($lastnotifications as $n) {
891             $notificationid = core_message_external::mark_notification_read($n->id, time());
892             $notificationids[] = external_api::clean_returnvalue(core_message_external::mark_notification_read_returns(),
893                 $notificationid);
894         }
896         // Retrieve all notifications sent (they are currently read).
897         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, true);
898         $this->assertCount(2, $lastnotifications);
899         $this->assertArrayHasKey($notificationids[1]['notificationid'], $lastnotifications);
900         $this->assertArrayHasKey($notificationids[0]['notificationid'], $lastnotifications);
902         // Retrieve all notifications sent by any user (that are currently unread).
903         $lastnotifications = message_get_messages($user1->id, 0, 1, false);
904         $this->assertCount(1, $lastnotifications);
906         // Invalid notification ids.
907         try {
908             $notificationid = core_message_external::mark_notification_read(1337, time());
909             $this->fail('Exception expected due invalid notificationid.');
910         } catch (dml_missing_record_exception $e) {
911             $this->assertEquals('invalidrecord', $e->errorcode);
912         }
914         // A notification to a different user.
915         $lastnotifications = message_get_messages($user2->id, $user3->id, 1, false);
916         $notificationid = array_pop($lastnotifications)->id;
917         try {
918             $notificationid = core_message_external::mark_notification_read($notificationid, time());
919             $this->fail('Exception expected due invalid notificationid.');
920         } catch (invalid_parameter_exception $e) {
921             $this->assertEquals('invalidparameter', $e->errorcode);
922         }
923     }
925     /**
926      * Test delete_message.
927      */
928     public function test_delete_message() {
929         global $DB;
930         $this->resetAfterTest(true);
932         $user1 = self::getDataGenerator()->create_user();
933         $user2 = self::getDataGenerator()->create_user();
934         $user3 = self::getDataGenerator()->create_user();
935         $user4 = self::getDataGenerator()->create_user();
937         // Login as user1.
938         $this->setUser($user1);
939         $this->assertEquals(array(), core_message_external::create_contacts(array($user2->id, $user3->id)));
941         // User user1 does not interchange messages with user3.
942         $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
943         $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
944         $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
945         $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
947         // Retrieve all messages sent by user2 (they are currently unread).
948         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
950         // Delete a message not read, as a user from.
951         $result = core_message_external::delete_message($m1to2, $user1->id, false);
952         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
953         $this->assertTrue($result['status']);
954         $this->assertCount(0, $result['warnings']);
955         $mua = $DB->get_record('message_user_actions', array('messageid' => $m1to2, 'userid' => $user1->id));
956         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua->action);
958         // Try to delete the same message again.
959         $result = core_message_external::delete_message($m1to2, $user1->id, false);
960         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
961         $this->assertFalse($result['status']);
963         // Try to delete a message that does not belong to me.
964         try {
965             $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
966             $this->fail('Exception expected due invalid messageid.');
967         } catch (moodle_exception $e) {
968             $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
969         }
971         $this->setUser($user3);
972         // Delete a message not read, as a user to.
973         $result = core_message_external::delete_message($m2to3, $user3->id, false);
974         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
975         $this->assertTrue($result['status']);
976         $this->assertCount(0, $result['warnings']);
977         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m2to3, 'userid' => $user3->id,
978             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
980         // Delete a message read.
981         $message = $DB->get_record('messages', ['id' => $m3to2]);
982         \core_message\api::mark_message_as_read($user3->id, $message, time());
983         $result = core_message_external::delete_message($m3to2, $user3->id);
984         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
985         $this->assertTrue($result['status']);
986         $this->assertCount(0, $result['warnings']);
987         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to2, 'userid' => $user3->id,
988             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
990         // Invalid message ids.
991         try {
992             $result = core_message_external::delete_message(-1, $user1->id);
993             $this->fail('Exception expected due invalid messageid.');
994         } catch (dml_missing_record_exception $e) {
995             $this->assertEquals('invalidrecordunknown', $e->errorcode);
996         }
998         // Invalid user.
999         try {
1000             $result = core_message_external::delete_message($m1to2, -1, false);
1001             $this->fail('Exception expected due invalid user.');
1002         } catch (moodle_exception $e) {
1003             $this->assertEquals('invaliduser', $e->errorcode);
1004         }
1006         // Not active user.
1007         delete_user($user2);
1008         try {
1009             $result = core_message_external::delete_message($m1to2, $user2->id, false);
1010             $this->fail('Exception expected due invalid user.');
1011         } catch (moodle_exception $e) {
1012             $this->assertEquals('userdeleted', $e->errorcode);
1013         }
1015         // Now, as an admin, try to delete any message.
1016         $this->setAdminUser();
1017         $result = core_message_external::delete_message($m3to4, $user4->id, false);
1018         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1019         $this->assertTrue($result['status']);
1020         $this->assertCount(0, $result['warnings']);
1021         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to4, 'userid' => $user4->id,
1022             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1024     }
1026     public function test_mark_all_notifications_as_read_invalid_user_exception() {
1027         $this->resetAfterTest(true);
1029         $this->expectException('moodle_exception');
1030         core_message_external::mark_all_notifications_as_read(-2132131, 0);
1031     }
1033     public function test_mark_all_notifications_as_read_access_denied_exception() {
1034         $this->resetAfterTest(true);
1036         $sender = $this->getDataGenerator()->create_user();
1037         $user = $this->getDataGenerator()->create_user();
1039         $this->setUser($user);
1040         $this->expectException('moodle_exception');
1041         core_message_external::mark_all_notifications_as_read($sender->id, 0);
1042     }
1044     public function test_mark_all_notifications_as_read_missing_from_user_exception() {
1045         $this->resetAfterTest(true);
1047         $sender = $this->getDataGenerator()->create_user();
1049         $this->setUser($sender);
1050         $this->expectException('moodle_exception');
1051         core_message_external::mark_all_notifications_as_read($sender->id, 99999);
1052     }
1054     public function test_mark_all_notifications_as_read() {
1055         global $DB;
1057         $this->resetAfterTest(true);
1059         $sender1 = $this->getDataGenerator()->create_user();
1060         $sender2 = $this->getDataGenerator()->create_user();
1061         $sender3 = $this->getDataGenerator()->create_user();
1062         $recipient = $this->getDataGenerator()->create_user();
1064         $this->setUser($recipient);
1066         $this->send_message($sender1, $recipient, 'Notification', 1);
1067         $this->send_message($sender1, $recipient, 'Notification', 1);
1068         $this->send_message($sender2, $recipient, 'Notification', 1);
1069         $this->send_message($sender2, $recipient, 'Notification', 1);
1070         $this->send_message($sender3, $recipient, 'Notification', 1);
1071         $this->send_message($sender3, $recipient, 'Notification', 1);
1073         core_message_external::mark_all_notifications_as_read($recipient->id, $sender1->id);
1074         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1075         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1077         $this->assertCount(2, $readnotifications);
1078         $this->assertCount(4, $unreadnotifications);
1080         core_message_external::mark_all_notifications_as_read($recipient->id, 0);
1081         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1082         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1084         $this->assertCount(6, $readnotifications);
1085         $this->assertCount(0, $unreadnotifications);
1086     }
1088     /**
1089      * Test get_user_notification_preferences
1090      */
1091     public function test_get_user_notification_preferences() {
1092         $this->resetAfterTest(true);
1094         $user = self::getDataGenerator()->create_user();
1095         $this->setUser($user);
1097         // Set a couple of preferences to test.
1098         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
1099         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
1101         $prefs = core_message_external::get_user_notification_preferences();
1102         $prefs = external_api::clean_returnvalue(core_message_external::get_user_notification_preferences_returns(), $prefs);
1103         // Check processors.
1104         $this->assertGreaterThanOrEqual(2, count($prefs['preferences']['processors']));
1105         $this->assertEquals($user->id, $prefs['preferences']['userid']);
1107         // Check components.
1108         $this->assertGreaterThanOrEqual(8, count($prefs['preferences']['components']));
1110         // Check some preferences that we previously set.
1111         $found = 0;
1112         foreach ($prefs['preferences']['components'] as $component) {
1113             foreach ($component['notifications'] as $prefdata) {
1114                 if ($prefdata['preferencekey'] != 'message_provider_mod_assign_assign_notification') {
1115                     continue;
1116                 }
1117                 foreach ($prefdata['processors'] as $processor) {
1118                     if ($processor['name'] == 'popup') {
1119                         $this->assertTrue($processor['loggedin']['checked']);
1120                         $found++;
1121                     } else if ($processor['name'] == 'email') {
1122                         $this->assertTrue($processor['loggedoff']['checked']);
1123                         $found++;
1124                     }
1125                 }
1126             }
1127         }
1128         $this->assertEquals(2, $found);
1129     }
1131     /**
1132      * Test get_user_notification_preferences permissions
1133      */
1134     public function test_get_user_notification_preferences_permissions() {
1135         $this->resetAfterTest(true);
1137         $user = self::getDataGenerator()->create_user();
1138         $otheruser = self::getDataGenerator()->create_user();
1139         $this->setUser($user);
1141         $this->expectException('moodle_exception');
1142         $prefs = core_message_external::get_user_notification_preferences($otheruser->id);
1143     }
1145     /**
1146      * Tests searching users in a course.
1147      */
1148     public function test_messagearea_search_users_in_course() {
1149         $this->resetAfterTest(true);
1151         // Create some users.
1152         $user1 = new stdClass();
1153         $user1->firstname = 'User';
1154         $user1->lastname = 'One';
1155         $user1 = self::getDataGenerator()->create_user($user1);
1157         // The person doing the search.
1158         $this->setUser($user1);
1160         // Set the second user's status to online by setting their last access to now.
1161         $user2 = new stdClass();
1162         $user2->firstname = 'User';
1163         $user2->lastname = 'Two';
1164         $user2->lastaccess = time();
1165         $user2 = self::getDataGenerator()->create_user($user2);
1167         // Block the second user.
1168         message_block_contact($user2->id, $user1->id);
1170         $user3 = new stdClass();
1171         $user3->firstname = 'User';
1172         $user3->lastname = 'Three';
1173         $user3 = self::getDataGenerator()->create_user($user3);
1175         // Create a course.
1176         $course1 = new stdClass();
1177         $course1->fullname = 'Course';
1178         $course1->shortname = 'One';
1179         $course1 = $this->getDataGenerator()->create_course();
1181         // Enrol the user we are doing the search for and one user in the course.
1182         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1183         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1185         // Perform a search.
1186         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1188         // We need to execute the return values cleaning process to simulate the web service.
1189         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1190             $result);
1192         // Check that we only retrieved a user that was enrolled, and that the user performing the search was not returned.
1193         $users = $result['contacts'];
1194         $this->assertCount(1, $users);
1196         $user = $users[0];
1197         $this->assertEquals($user2->id, $user['userid']);
1198         $this->assertEquals(fullname($user2), $user['fullname']);
1199         $this->assertFalse($user['ismessaging']);
1200         $this->assertFalse($user['sentfromcurrentuser']);
1201         $this->assertNull($user['lastmessage']);
1202         $this->assertNull($user['messageid']);
1203         $this->assertNull($user['isonline']);
1204         $this->assertFalse($user['isread']);
1205         $this->assertTrue($user['isblocked']);
1206         $this->assertNull($user['unreadcount']);
1207     }
1209     /**
1210      * Tests searching users in course as another user.
1211      */
1212     public function test_messagearea_search_users_in_course_as_other_user() {
1213         $this->resetAfterTest(true);
1215         // The person doing the search for another user.
1216         $this->setAdminUser();
1218         // Create some users.
1219         $user1 = new stdClass();
1220         $user1->firstname = 'User';
1221         $user1->lastname = 'One';
1222         $user1 = self::getDataGenerator()->create_user($user1);
1224         $user2 = new stdClass();
1225         $user2->firstname = 'User';
1226         $user2->lastname = 'Two';
1227         $user2 = self::getDataGenerator()->create_user($user2);
1229         $user3 = new stdClass();
1230         $user3->firstname = 'User';
1231         $user3->lastname = 'Three';
1232         $user3 = self::getDataGenerator()->create_user($user3);
1234         // Create a course.
1235         $course1 = new stdClass();
1236         $course1->fullname = 'Course';
1237         $course1->shortname = 'One';
1238         $course1 = $this->getDataGenerator()->create_course();
1240         // Enrol the user we are doing the search for and one user in the course.
1241         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1242         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1244         // Perform a search.
1245         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1247         // We need to execute the return values cleaning process to simulate the web service server.
1248         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1249             $result);
1251         // Check that we got the user enrolled, and that the user we are performing the search on behalf of was not returned.
1252         $users = $result['contacts'];
1253         $this->assertCount(1, $users);
1255         $user = $users[0];
1256         $this->assertEquals($user2->id, $user['userid']);
1257         $this->assertEquals(fullname($user2), $user['fullname']);
1258         $this->assertFalse($user['ismessaging']);
1259         $this->assertFalse($user['sentfromcurrentuser']);
1260         $this->assertNull($user['lastmessage']);
1261         $this->assertNull($user['messageid']);
1262         $this->assertFalse($user['isonline']);
1263         $this->assertFalse($user['isread']);
1264         $this->assertFalse($user['isblocked']);
1265         $this->assertNull($user['unreadcount']);
1266     }
1268     /**
1269      * Tests searching users in course as another user without the proper capabilities.
1270      */
1271     public function test_messagearea_search_users_in_course_as_other_user_without_cap() {
1272         $this->resetAfterTest(true);
1274         // Create some users.
1275         $user1 = self::getDataGenerator()->create_user();
1276         $user2 = self::getDataGenerator()->create_user();
1278         // The person doing the search for another user.
1279         $this->setUser($user1);
1281         // Create a course.
1282         $course = $this->getDataGenerator()->create_course();
1284         // Ensure an exception is thrown.
1285         $this->expectException('moodle_exception');
1286         core_message_external::data_for_messagearea_search_users_in_course($user2->id, $course->id, 'User');
1287     }
1289     /**
1290      * Tests searching users in course with messaging disabled.
1291      */
1292     public function test_messagearea_search_users_in_course_messaging_disabled() {
1293         global $CFG;
1295         $this->resetAfterTest(true);
1297         // Create some skeleton data just so we can call the WS..
1298         $user = self::getDataGenerator()->create_user();
1299         $course = $this->getDataGenerator()->create_course();
1301         // The person doing the search for another user.
1302         $this->setUser($user);
1304         // Disable messaging.
1305         $CFG->messaging = 0;
1307         // Ensure an exception is thrown.
1308         $this->expectException('moodle_exception');
1309         core_message_external::data_for_messagearea_search_users_in_course($user->id, $course->id, 'User');
1310     }
1312     /**
1313      * Tests searching users.
1314      */
1315     public function test_messagearea_search_users() {
1316         $this->resetAfterTest(true);
1318         // Create some users.
1319         $user1 = new stdClass();
1320         $user1->firstname = 'User';
1321         $user1->lastname = 'One';
1322         $user1 = self::getDataGenerator()->create_user($user1);
1324         // Set as the user performing the search.
1325         $this->setUser($user1);
1327         $user2 = new stdClass();
1328         $user2->firstname = 'User search';
1329         $user2->lastname = 'Two';
1330         $user2 = self::getDataGenerator()->create_user($user2);
1332         $user3 = new stdClass();
1333         $user3->firstname = 'User search';
1334         $user3->lastname = 'Three';
1335         $user3 = self::getDataGenerator()->create_user($user3);
1337         $user4 = new stdClass();
1338         $user4->firstname = 'User';
1339         $user4->lastname = 'Four';
1340         $user4 = self::getDataGenerator()->create_user($user4);
1342         $user5 = new stdClass();
1343         $user5->firstname = 'User search';
1344         $user5->lastname = 'Five';
1345         $user5 = self::getDataGenerator()->create_user($user5);
1347         $user6 = new stdClass();
1348         $user6->firstname = 'User';
1349         $user6->lastname = 'Six';
1350         $user6 = self::getDataGenerator()->create_user($user6);
1352         // Create some courses.
1353         $course1 = new stdClass();
1354         $course1->fullname = 'Course search';
1355         $course1->shortname = 'One';
1356         $course1 = $this->getDataGenerator()->create_course($course1);
1358         $course2 = new stdClass();
1359         $course2->fullname = 'Course';
1360         $course2->shortname = 'Two';
1361         $course2 = $this->getDataGenerator()->create_course($course2);
1363         $course3 = new stdClass();
1364         $course3->fullname = 'Course';
1365         $course3->shortname = 'Three search';
1366         $course3 = $this->getDataGenerator()->create_course($course3);
1368         $course4 = new stdClass();
1369         $course4->fullname = 'Course Four';
1370         $course4->shortname = 'CF100';
1371         $course4 = $this->getDataGenerator()->create_course($course4);
1373         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
1374         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'student');
1375         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 'student');
1377         // Add some users as contacts.
1378         message_add_contact($user2->id, 0, $user1->id);
1379         message_add_contact($user3->id, 0, $user1->id);
1380         message_add_contact($user4->id, 0, $user1->id);
1382         // Perform a search.
1383         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
1385         // We need to execute the return values cleaning process to simulate the web service server.
1386         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
1387             $result);
1389         // Confirm that we returns contacts, courses and non-contacts.
1390         $contacts = $result['contacts'];
1391         $courses = $result['courses'];
1392         $noncontacts = $result['noncontacts'];
1394         // Check that we retrieved the correct contacts.
1395         $this->assertCount(2, $contacts);
1396         $this->assertEquals($user3->id, $contacts[0]['userid']);
1397         $this->assertEquals($user2->id, $contacts[1]['userid']);
1399         // Check that we retrieved the correct courses.
1400         $this->assertCount(2, $courses);
1401         $this->assertEquals($course3->id, $courses[0]['id']);
1402         $this->assertEquals($course1->id, $courses[1]['id']);
1404         // Check that we retrieved the correct non-contacts.
1405         $this->assertCount(1, $noncontacts);
1406         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
1407     }
1409     /**
1410      * Tests searching users as another user.
1411      */
1412     public function test_messagearea_search_users_as_other_user() {
1413         $this->resetAfterTest(true);
1415         // The person doing the search.
1416         $this->setAdminUser();
1418         // Create some users.
1419         $user1 = new stdClass();
1420         $user1->firstname = 'User';
1421         $user1->lastname = 'One';
1422         $user1 = self::getDataGenerator()->create_user($user1);
1424         $user2 = new stdClass();
1425         $user2->firstname = 'User search';
1426         $user2->lastname = 'Two';
1427         $user2 = self::getDataGenerator()->create_user($user2);
1429         $user3 = new stdClass();
1430         $user3->firstname = 'User search';
1431         $user3->lastname = 'Three';
1432         $user3 = self::getDataGenerator()->create_user($user3);
1434         $user4 = new stdClass();
1435         $user4->firstname = 'User';
1436         $user4->lastname = 'Four';
1437         $user4 = self::getDataGenerator()->create_user($user4);
1439         $user5 = new stdClass();
1440         $user5->firstname = 'User search';
1441         $user5->lastname = 'Five';
1442         $user5 = self::getDataGenerator()->create_user($user5);
1444         $user6 = new stdClass();
1445         $user6->firstname = 'User';
1446         $user6->lastname = 'Six';
1447         $user6 = self::getDataGenerator()->create_user($user6);
1449         // Create some courses.
1450         $course1 = new stdClass();
1451         $course1->fullname = 'Course search';
1452         $course1->shortname = 'One';
1453         $course1 = $this->getDataGenerator()->create_course($course1);
1455         $course2 = new stdClass();
1456         $course2->fullname = 'Course';
1457         $course2->shortname = 'Two';
1458         $course2 = $this->getDataGenerator()->create_course($course2);
1460         $course3 = new stdClass();
1461         $course3->fullname = 'Course';
1462         $course3->shortname = 'Three search';
1463         $course3 = $this->getDataGenerator()->create_course($course3);
1465         // Add some users as contacts.
1466         message_add_contact($user2->id, 0, $user1->id);
1467         message_add_contact($user3->id, 0, $user1->id);
1468         message_add_contact($user4->id, 0, $user1->id);
1470         // Perform a search.
1471         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
1473         // We need to execute the return values cleaning process to simulate the web service server.
1474         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
1475             $result);
1477         // Confirm that we returns contacts, courses and non-contacts.
1478         $contacts = $result['contacts'];
1479         $courses = $result['courses'];
1480         $noncontacts = $result['noncontacts'];
1482         // Check that we retrieved the correct contacts.
1483         $this->assertCount(2, $contacts);
1484         $this->assertEquals($user3->id, $contacts[0]['userid']);
1485         $this->assertEquals($user2->id, $contacts[1]['userid']);
1487         // Check that we retrieved the correct courses.
1488         $this->assertCount(0, $courses);
1490         // Check that we retrieved the correct non-contacts.
1491         $this->assertCount(1, $noncontacts);
1492         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
1493     }
1495     /**
1496      * Tests searching users as another user without the proper capabilities.
1497      */
1498     public function test_messagearea_search_users_as_other_user_without_cap() {
1499         $this->resetAfterTest(true);
1501         // Create some users.
1502         $user1 = self::getDataGenerator()->create_user();
1503         $user2 = self::getDataGenerator()->create_user();
1505         // The person doing the search for another user.
1506         $this->setUser($user1);
1508         // Ensure an exception is thrown.
1509         $this->expectException('moodle_exception');
1510         core_message_external::data_for_messagearea_search_users($user2->id, 'User');
1511     }
1513     /**
1514      * Tests searching users with messaging disabled.
1515      */
1516     public function test_messagearea_search_users_messaging_disabled() {
1517         global $CFG;
1519         $this->resetAfterTest(true);
1521         // Create some skeleton data just so we can call the WS.
1522         $user = self::getDataGenerator()->create_user();
1524         // The person doing the search.
1525         $this->setUser($user);
1527         // Disable messaging.
1528         $CFG->messaging = 0;
1530         // Ensure an exception is thrown.
1531         $this->expectException('moodle_exception');
1532         core_message_external::data_for_messagearea_search_users($user->id, 'User');
1533     }
1535     /**
1536      * Tests searching messages.
1537      */
1538     public function test_messagearea_search_messages() {
1539         $this->resetAfterTest(true);
1541         // Create some users.
1542         $user1 = self::getDataGenerator()->create_user();
1543         $user2 = self::getDataGenerator()->create_user();
1545         // The person doing the search.
1546         $this->setUser($user1);
1548         // Send some messages back and forth.
1549         $time = time();
1550         $this->send_message($user1, $user2, 'Yo!', 0, $time);
1551         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
1552         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
1553         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
1555         // Perform a search.
1556         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
1558         // We need to execute the return values cleaning process to simulate the web service server.
1559         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
1560             $result);
1562         // Confirm the data is correct.
1563         $messages = $result['contacts'];
1564         $this->assertCount(2, $messages);
1566         $message1 = $messages[0];
1567         $message2 = $messages[1];
1569         $this->assertEquals($user2->id, $message1['userid']);
1570         $this->assertEquals(fullname($user2), $message1['fullname']);
1571         $this->assertTrue($message1['ismessaging']);
1572         $this->assertFalse($message1['sentfromcurrentuser']);
1573         $this->assertEquals('Word.', $message1['lastmessage']);
1574         $this->assertNotEmpty($message1['messageid']);
1575         $this->assertNull($message1['isonline']);
1576         $this->assertFalse($message1['isread']);
1577         $this->assertFalse($message1['isblocked']);
1578         $this->assertNull($message1['unreadcount']);
1580         $this->assertEquals($user2->id, $message2['userid']);
1581         $this->assertEquals(fullname($user2), $message2['fullname']);
1582         $this->assertTrue($message2['ismessaging']);
1583         $this->assertTrue($message2['sentfromcurrentuser']);
1584         $this->assertEquals('Yo!', $message2['lastmessage']);
1585         $this->assertNotEmpty($message2['messageid']);
1586         $this->assertNull($message2['isonline']);
1587         $this->assertTrue($message2['isread']);
1588         $this->assertFalse($message2['isblocked']);
1589         $this->assertNull($message2['unreadcount']);
1590     }
1592     /**
1593      * Tests searching messages as another user.
1594      */
1595     public function test_messagearea_search_messages_as_other_user() {
1596         $this->resetAfterTest(true);
1598         // The person doing the search.
1599         $this->setAdminUser();
1601         // Create some users.
1602         $user1 = self::getDataGenerator()->create_user();
1603         $user2 = self::getDataGenerator()->create_user();
1605         // Send some messages back and forth.
1606         $time = time();
1607         $this->send_message($user1, $user2, 'Yo!', 0, $time);
1608         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
1609         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
1610         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
1612         // Perform a search.
1613         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
1615         // We need to execute the return values cleaning process to simulate the web service server.
1616         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
1617             $result);
1619         // Confirm the data is correct.
1620         $messages = $result['contacts'];
1621         $this->assertCount(2, $messages);
1623         $message1 = $messages[0];
1624         $message2 = $messages[1];
1626         $this->assertEquals($user2->id, $message1['userid']);
1627         $this->assertEquals(fullname($user2), $message1['fullname']);
1628         $this->assertTrue($message1['ismessaging']);
1629         $this->assertFalse($message1['sentfromcurrentuser']);
1630         $this->assertEquals('Word.', $message1['lastmessage']);
1631         $this->assertNotEmpty($message1['messageid']);
1632         $this->assertFalse($message1['isonline']);
1633         $this->assertFalse($message1['isread']);
1634         $this->assertFalse($message1['isblocked']);
1635         $this->assertNull($message1['unreadcount']);
1637         $this->assertEquals($user2->id, $message2['userid']);
1638         $this->assertEquals(fullname($user2), $message2['fullname']);
1639         $this->assertTrue($message2['ismessaging']);
1640         $this->assertTrue($message2['sentfromcurrentuser']);
1641         $this->assertEquals('Yo!', $message2['lastmessage']);
1642         $this->assertNotEmpty($message2['messageid']);
1643         $this->assertFalse($message2['isonline']);
1644         $this->assertTrue($message2['isread']);
1645         $this->assertFalse($message2['isblocked']);
1646         $this->assertNull($message2['unreadcount']);
1647     }
1649     /**
1650      * Tests searching messages as another user without the proper capabilities.
1651      */
1652     public function test_messagearea_search_messages_as_other_user_without_cap() {
1653         $this->resetAfterTest(true);
1655         // Create some users.
1656         $user1 = self::getDataGenerator()->create_user();
1657         $user2 = self::getDataGenerator()->create_user();
1659         // The person doing the search for another user.
1660         $this->setUser($user1);
1662         // Ensure an exception is thrown.
1663         $this->expectException('moodle_exception');
1664         core_message_external::data_for_messagearea_search_messages($user2->id, 'Search');
1665     }
1667     /**
1668      * Tests searching messages with messaging disabled
1669      */
1670     public function test_messagearea_search_messages_messaging_disabled() {
1671         global $CFG;
1673         $this->resetAfterTest(true);
1675         // Create some skeleton data just so we can call the WS.
1676         $user = self::getDataGenerator()->create_user();
1678         // The person doing the search .
1679         $this->setUser($user);
1681         // Disable messaging.
1682         $CFG->messaging = 0;
1684         // Ensure an exception is thrown.
1685         $this->expectException('moodle_exception');
1686         core_message_external::data_for_messagearea_search_messages($user->id, 'Search');
1687     }
1689     /**
1690      * Tests retrieving conversations.
1691      */
1692     public function test_messagearea_conversations() {
1693         $this->resetAfterTest(true);
1695         // Create some users.
1696         $user1 = self::getDataGenerator()->create_user();
1697         $user2 = self::getDataGenerator()->create_user();
1698         $user3 = self::getDataGenerator()->create_user();
1699         $user4 = self::getDataGenerator()->create_user();
1701         // The person retrieving the conversations.
1702         $this->setUser($user1);
1704         // Send some messages back and forth, have some different conversations with different users.
1705         $time = time();
1706         $this->send_message($user1, $user2, 'Yo!', 0, $time);
1707         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
1708         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
1709         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
1711         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
1712         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
1713         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
1714         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
1716         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
1717         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
1718         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
1720         // Retrieve the conversations.
1721         $result = core_message_external::data_for_messagearea_conversations($user1->id);
1723         // We need to execute the return values cleaning process to simulate the web service server.
1724         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
1725             $result);
1727         // Confirm the data is correct.
1728         $messages = $result['contacts'];
1729         $this->assertCount(3, $messages);
1731         $message1 = $messages[0];
1732         $message2 = $messages[1];
1733         $message3 = $messages[2];
1735         $this->assertEquals($user4->id, $message1['userid']);
1736         $this->assertTrue($message1['ismessaging']);
1737         $this->assertTrue($message1['sentfromcurrentuser']);
1738         $this->assertEquals('Dope.', $message1['lastmessage']);
1739         $this->assertEquals($messageid3, $message1['messageid']);
1740         $this->assertNull($message1['isonline']);
1741         $this->assertFalse($message1['isread']);
1742         $this->assertFalse($message1['isblocked']);
1743         $this->assertEquals(1, $message1['unreadcount']);
1745         $this->assertEquals($user3->id, $message2['userid']);
1746         $this->assertTrue($message2['ismessaging']);
1747         $this->assertFalse($message2['sentfromcurrentuser']);
1748         $this->assertEquals('Cool.', $message2['lastmessage']);
1749         $this->assertEquals($messageid2, $message2['messageid']);
1750         $this->assertNull($message2['isonline']);
1751         $this->assertFalse($message2['isread']);
1752         $this->assertFalse($message2['isblocked']);
1753         $this->assertEquals(2, $message2['unreadcount']);
1755         $this->assertEquals($user2->id, $message3['userid']);
1756         $this->assertTrue($message3['ismessaging']);
1757         $this->assertFalse($message3['sentfromcurrentuser']);
1758         $this->assertEquals('Word.', $message3['lastmessage']);
1759         $this->assertEquals($messageid1, $message3['messageid']);
1760         $this->assertNull($message3['isonline']);
1761         $this->assertFalse($message3['isread']);
1762         $this->assertFalse($message3['isblocked']);
1763         $this->assertEquals(2, $message3['unreadcount']);
1764     }
1766     /**
1767      * Tests retrieving conversations as another user.
1768      */
1769     public function test_messagearea_conversations_as_other_user() {
1770         $this->resetAfterTest(true);
1772         // Set as admin.
1773         $this->setAdminUser();
1775         // Create some users.
1776         $user1 = self::getDataGenerator()->create_user();
1777         $user2 = self::getDataGenerator()->create_user();
1778         $user3 = self::getDataGenerator()->create_user();
1779         $user4 = self::getDataGenerator()->create_user();
1781         // Send some messages back and forth, have some different conversations with different users.
1782         $time = time();
1783         $this->send_message($user1, $user2, 'Yo!', 0, $time);
1784         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
1785         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
1786         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
1788         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
1789         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
1790         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
1791         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
1793         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
1794         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
1795         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
1797         // Retrieve the conversations.
1798         $result = core_message_external::data_for_messagearea_conversations($user1->id);
1800         // We need to execute the return values cleaning process to simulate the web service server.
1801         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
1802             $result);
1804         // Confirm the data is correct.
1805         $messages = $result['contacts'];
1806         $this->assertCount(3, $messages);
1808         $message1 = $messages[0];
1809         $message2 = $messages[1];
1810         $message3 = $messages[2];
1812         $this->assertEquals($user4->id, $message1['userid']);
1813         $this->assertTrue($message1['ismessaging']);
1814         $this->assertTrue($message1['sentfromcurrentuser']);
1815         $this->assertEquals('Dope.', $message1['lastmessage']);
1816         $this->assertEquals($messageid3, $message1['messageid']);
1817         $this->assertFalse($message1['isonline']);
1818         $this->assertFalse($message1['isread']);
1819         $this->assertFalse($message1['isblocked']);
1820         $this->assertEquals(1, $message1['unreadcount']);
1822         $this->assertEquals($user3->id, $message2['userid']);
1823         $this->assertTrue($message2['ismessaging']);
1824         $this->assertFalse($message2['sentfromcurrentuser']);
1825         $this->assertEquals('Cool.', $message2['lastmessage']);
1826         $this->assertEquals($messageid2, $message2['messageid']);
1827         $this->assertFalse($message2['isonline']);
1828         $this->assertFalse($message2['isread']);
1829         $this->assertFalse($message2['isblocked']);
1830         $this->assertEquals(2, $message2['unreadcount']);
1832         $this->assertEquals($user2->id, $message3['userid']);
1833         $this->assertTrue($message3['ismessaging']);
1834         $this->assertFalse($message3['sentfromcurrentuser']);
1835         $this->assertEquals('Word.', $message3['lastmessage']);
1836         $this->assertEquals($messageid1, $message3['messageid']);
1837         $this->assertFalse($message3['isonline']);
1838         $this->assertFalse($message3['isread']);
1839         $this->assertFalse($message3['isblocked']);
1840         $this->assertEquals(2, $message3['unreadcount']);
1841     }
1843     /**
1844      * Tests retrieving conversations as another user without the proper capabilities.
1845      */
1846     public function test_messagearea_conversations_as_other_user_without_cap() {
1847         $this->resetAfterTest(true);
1849         // Create some users.
1850         $user1 = self::getDataGenerator()->create_user();
1851         $user2 = self::getDataGenerator()->create_user();
1853         // The person retrieving the conversations for another user.
1854         $this->setUser($user1);
1856         // Ensure an exception is thrown.
1857         $this->expectException('moodle_exception');
1858         core_message_external::data_for_messagearea_conversations($user2->id);
1859     }
1861     /**
1862      * Tests retrieving conversations with messaging disabled.
1863      */
1864     public function test_messagearea_conversations_messaging_disabled() {
1865         global $CFG;
1867         $this->resetAfterTest(true);
1869         // Create some skeleton data just so we can call the WS.
1870         $user = self::getDataGenerator()->create_user();
1872         // The person retrieving the conversations.
1873         $this->setUser($user);
1875         // Disable messaging.
1876         $CFG->messaging = 0;
1878         // Ensure an exception is thrown.
1879         $this->expectException('moodle_exception');
1880         core_message_external::data_for_messagearea_conversations($user->id);
1881     }
1883     /**
1884      * Tests retrieving contacts.
1885      */
1886     public function test_messagearea_contacts() {
1887         $this->resetAfterTest(true);
1889         // Create some users.
1890         $user1 = self::getDataGenerator()->create_user();
1892         // Set as the user.
1893         $this->setUser($user1);
1895         $user2 = new stdClass();
1896         $user2->firstname = 'User';
1897         $user2->lastname = 'A';
1898         $user2 = self::getDataGenerator()->create_user($user2);
1900         $user3 = new stdClass();
1901         $user3->firstname = 'User';
1902         $user3->lastname = 'B';
1903         $user3 = self::getDataGenerator()->create_user($user3);
1905         $user4 = new stdClass();
1906         $user4->firstname = 'User';
1907         $user4->lastname = 'C';
1908         $user4 = self::getDataGenerator()->create_user($user4);
1910         $user5 = new stdClass();
1911         $user5->firstname = 'User';
1912         $user5->lastname = 'D';
1913         $user5 = self::getDataGenerator()->create_user($user5);
1915         // Add some users as contacts.
1916         message_add_contact($user2->id, 0, $user1->id);
1917         message_add_contact($user3->id, 0, $user1->id);
1918         message_add_contact($user4->id, 0, $user1->id);
1920         // Retrieve the contacts.
1921         $result = core_message_external::data_for_messagearea_contacts($user1->id);
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_contacts_returns(),
1925             $result);
1927         // Confirm the data is correct.
1928         $contacts = $result['contacts'];
1929         $this->assertCount(3, $contacts);
1931         $contact1 = $contacts[0];
1932         $contact2 = $contacts[1];
1933         $contact3 = $contacts[2];
1935         $this->assertEquals($user2->id, $contact1['userid']);
1936         $this->assertFalse($contact1['ismessaging']);
1937         $this->assertFalse($contact1['sentfromcurrentuser']);
1938         $this->assertNull($contact1['lastmessage']);
1939         $this->assertNull($contact1['messageid']);
1940         $this->assertNull($contact1['isonline']);
1941         $this->assertFalse($contact1['isread']);
1942         $this->assertFalse($contact1['isblocked']);
1943         $this->assertNull($contact1['unreadcount']);
1945         $this->assertEquals($user3->id, $contact2['userid']);
1946         $this->assertFalse($contact2['ismessaging']);
1947         $this->assertFalse($contact2['sentfromcurrentuser']);
1948         $this->assertNull($contact2['lastmessage']);
1949         $this->assertNull($contact2['messageid']);
1950         $this->assertNull($contact2['isonline']);
1951         $this->assertFalse($contact2['isread']);
1952         $this->assertFalse($contact2['isblocked']);
1953         $this->assertNull($contact2['unreadcount']);
1955         $this->assertEquals($user4->id, $contact3['userid']);
1956         $this->assertFalse($contact3['ismessaging']);
1957         $this->assertFalse($contact3['sentfromcurrentuser']);
1958         $this->assertNull($contact3['lastmessage']);
1959         $this->assertNull($contact3['messageid']);
1960         $this->assertNull($contact3['isonline']);
1961         $this->assertFalse($contact3['isread']);
1962         $this->assertFalse($contact3['isblocked']);
1963         $this->assertNull($contact3['unreadcount']);
1964     }
1966     /**
1967      * Tests retrieving contacts as another user.
1968      */
1969     public function test_messagearea_contacts_as_other_user() {
1970         $this->resetAfterTest(true);
1972         $this->setAdminUser();
1974         // Create some users.
1975         $user1 = self::getDataGenerator()->create_user();
1977         $user2 = new stdClass();
1978         $user2->firstname = 'User';
1979         $user2->lastname = 'A';
1980         $user2 = self::getDataGenerator()->create_user($user2);
1982         $user3 = new stdClass();
1983         $user3->firstname = 'User';
1984         $user3->lastname = 'B';
1985         $user3 = self::getDataGenerator()->create_user($user3);
1987         $user4 = new stdClass();
1988         $user4->firstname = 'User';
1989         $user4->lastname = 'C';
1990         $user4 = self::getDataGenerator()->create_user($user4);
1992         $user5 = new stdClass();
1993         $user5->firstname = 'User';
1994         $user5->lastname = 'D';
1995         $user5 = self::getDataGenerator()->create_user($user5);
1997         // Add some users as contacts.
1998         message_add_contact($user2->id, 0, $user1->id);
1999         message_add_contact($user3->id, 0, $user1->id);
2000         message_add_contact($user4->id, 0, $user1->id);
2002         // Retrieve the contacts.
2003         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2005         // We need to execute the return values cleaning process to simulate the web service server.
2006         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2007             $result);
2009         // Confirm the data is correct.
2010         $contacts = $result['contacts'];
2011         $this->assertCount(3, $contacts);
2013         $contact1 = $contacts[0];
2014         $contact2 = $contacts[1];
2015         $contact3 = $contacts[2];
2017         $this->assertEquals($user2->id, $contact1['userid']);
2018         $this->assertFalse($contact1['ismessaging']);
2019         $this->assertFalse($contact1['sentfromcurrentuser']);
2020         $this->assertNull($contact1['lastmessage']);
2021         $this->assertNull($contact1['messageid']);
2022         $this->assertFalse($contact1['isonline']);
2023         $this->assertFalse($contact1['isread']);
2024         $this->assertFalse($contact1['isblocked']);
2025         $this->assertNull($contact1['unreadcount']);
2027         $this->assertEquals($user3->id, $contact2['userid']);
2028         $this->assertFalse($contact2['ismessaging']);
2029         $this->assertFalse($contact2['sentfromcurrentuser']);
2030         $this->assertNull($contact2['lastmessage']);
2031         $this->assertNull($contact2['messageid']);
2032         $this->assertFalse($contact2['isonline']);
2033         $this->assertFalse($contact2['isread']);
2034         $this->assertFalse($contact2['isblocked']);
2035         $this->assertNull($contact2['unreadcount']);
2037         $this->assertEquals($user4->id, $contact3['userid']);
2038         $this->assertFalse($contact3['ismessaging']);
2039         $this->assertFalse($contact3['sentfromcurrentuser']);
2040         $this->assertNull($contact3['lastmessage']);
2041         $this->assertNull($contact3['messageid']);
2042         $this->assertFalse($contact3['isonline']);
2043         $this->assertFalse($contact3['isread']);
2044         $this->assertFalse($contact3['isblocked']);
2045         $this->assertNull($contact3['unreadcount']);
2046     }
2048     /**
2049      * Tests retrieving contacts as another user without the proper capabilities.
2050      */
2051     public function test_messagearea_contacts_as_other_user_without_cap() {
2052         $this->resetAfterTest(true);
2054         // Create some users.
2055         $user1 = self::getDataGenerator()->create_user();
2056         $user2 = self::getDataGenerator()->create_user();
2058         // The person retrieving the contacts for another user.
2059         $this->setUser($user1);
2061         // Perform the WS call and ensure an exception is thrown.
2062         $this->expectException('moodle_exception');
2063         core_message_external::data_for_messagearea_contacts($user2->id);
2064     }
2066     /**
2067      * Tests retrieving contacts with messaging disabled.
2068      */
2069     public function test_messagearea_contacts_messaging_disabled() {
2070         global $CFG;
2072         $this->resetAfterTest(true);
2074         // Create some skeleton data just so we can call the WS.
2075         $user = self::getDataGenerator()->create_user();
2077         // The person retrieving the contacts.
2078         $this->setUser($user);
2080         // Disable messaging.
2081         $CFG->messaging = 0;
2083         // Perform the WS call and ensure we are shown that it is disabled.
2084         $this->expectException('moodle_exception');
2085         core_message_external::data_for_messagearea_contacts($user->id);
2086     }
2088     /**
2089      * Tests retrieving messages.
2090      */
2091     public function test_messagearea_messages() {
2092         $this->resetAfterTest(true);
2094         // Create some users.
2095         $user1 = self::getDataGenerator()->create_user();
2096         $user2 = self::getDataGenerator()->create_user();
2098         // The person asking for the messages.
2099         $this->setUser($user1);
2101         // Send some messages back and forth.
2102         $time = time();
2103         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2104         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2105         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2106         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2108         // Retrieve the messages.
2109         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2111         // We need to execute the return values cleaning process to simulate the web service server.
2112         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2113             $result);
2115         // Check the results are correct.
2116         $this->assertTrue($result['iscurrentuser']);
2117         $this->assertEquals($user1->id, $result['currentuserid']);
2118         $this->assertEquals($user2->id, $result['otheruserid']);
2119         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2120         $this->assertNull($result['isonline']);
2122         // Confirm the message data is correct.
2123         $messages = $result['messages'];
2124         $this->assertCount(4, $messages);
2126         $message1 = $messages[0];
2127         $message2 = $messages[1];
2128         $message3 = $messages[2];
2129         $message4 = $messages[3];
2131         $this->assertEquals($user1->id, $message1['useridfrom']);
2132         $this->assertEquals($user2->id, $message1['useridto']);
2133         $this->assertTrue($message1['displayblocktime']);
2134         $this->assertContains('Yo!', $message1['text']);
2136         $this->assertEquals($user2->id, $message2['useridfrom']);
2137         $this->assertEquals($user1->id, $message2['useridto']);
2138         $this->assertFalse($message2['displayblocktime']);
2139         $this->assertContains('Sup mang?', $message2['text']);
2141         $this->assertEquals($user1->id, $message3['useridfrom']);
2142         $this->assertEquals($user2->id, $message3['useridto']);
2143         $this->assertFalse($message3['displayblocktime']);
2144         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2146         $this->assertEquals($user2->id, $message4['useridfrom']);
2147         $this->assertEquals($user1->id, $message4['useridto']);
2148         $this->assertFalse($message4['displayblocktime']);
2149         $this->assertContains('Word.', $message4['text']);
2150     }
2152     /**
2153      * Tests retrieving messages.
2154      */
2155     public function test_messagearea_messages_timefrom() {
2156         $this->resetAfterTest(true);
2158         // Create some users.
2159         $user1 = self::getDataGenerator()->create_user();
2160         $user2 = self::getDataGenerator()->create_user();
2162         // The person asking for the messages.
2163         $this->setUser($user1);
2165         // Send some messages back and forth.
2166         $time = time();
2167         $this->send_message($user1, $user2, 'Message 1', 0, $time - 4);
2168         $this->send_message($user2, $user1, 'Message 2', 0, $time - 3);
2169         $this->send_message($user1, $user2, 'Message 3', 0, $time - 2);
2170         $this->send_message($user2, $user1, 'Message 4', 0, $time - 1);
2172         // Retrieve the messages from $time - 3, which should be the 3 most recent messages.
2173         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id, 0, 0, false, $time - 3);
2175         // We need to execute the return values cleaning process to simulate the web service server.
2176         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2177             $result);
2179         // Confirm the message data is correct. We shouldn't get 'Message 1' back.
2180         $messages = $result['messages'];
2181         $this->assertCount(3, $messages);
2183         $message1 = $messages[0];
2184         $message2 = $messages[1];
2185         $message3 = $messages[2];
2187         $this->assertContains('Message 2', $message1['text']);
2188         $this->assertContains('Message 3', $message2['text']);
2189         $this->assertContains('Message 4', $message3['text']);
2190     }
2192     /**
2193      * Tests retrieving messages as another user.
2194      */
2195     public function test_messagearea_messages_as_other_user() {
2196         $this->resetAfterTest(true);
2198         // Set as admin.
2199         $this->setAdminUser();
2201         // Create some users.
2202         $user1 = self::getDataGenerator()->create_user();
2203         $user2 = self::getDataGenerator()->create_user();
2205         // Send some messages back and forth.
2206         $time = time();
2207         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2208         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2209         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2210         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2212         // Retrieve the messages.
2213         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2215         // We need to execute the return values cleaning process to simulate the web service server.
2216         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2217             $result);
2219         // Check the results are correct.
2220         $this->assertFalse($result['iscurrentuser']);
2221         $this->assertEquals($user1->id, $result['currentuserid']);
2222         $this->assertEquals($user2->id, $result['otheruserid']);
2223         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2224         $this->assertFalse($result['isonline']);
2226         // Confirm the message data is correct.
2227         $messages = $result['messages'];
2228         $this->assertCount(4, $messages);
2230         $message1 = $messages[0];
2231         $message2 = $messages[1];
2232         $message3 = $messages[2];
2233         $message4 = $messages[3];
2235         $this->assertEquals($user1->id, $message1['useridfrom']);
2236         $this->assertEquals($user2->id, $message1['useridto']);
2237         $this->assertTrue($message1['displayblocktime']);
2238         $this->assertContains('Yo!', $message1['text']);
2240         $this->assertEquals($user2->id, $message2['useridfrom']);
2241         $this->assertEquals($user1->id, $message2['useridto']);
2242         $this->assertFalse($message2['displayblocktime']);
2243         $this->assertContains('Sup mang?', $message2['text']);
2245         $this->assertEquals($user1->id, $message3['useridfrom']);
2246         $this->assertEquals($user2->id, $message3['useridto']);
2247         $this->assertFalse($message3['displayblocktime']);
2248         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2250         $this->assertEquals($user2->id, $message4['useridfrom']);
2251         $this->assertEquals($user1->id, $message4['useridto']);
2252         $this->assertFalse($message4['displayblocktime']);
2253         $this->assertContains('Word.', $message4['text']);
2254     }
2256     /**
2257      * Tests retrieving messages as another user without the proper capabilities.
2258      */
2259     public function test_messagearea_messages_as_other_user_without_cap() {
2260         $this->resetAfterTest(true);
2262         // Create some users.
2263         $user1 = self::getDataGenerator()->create_user();
2264         $user2 = self::getDataGenerator()->create_user();
2265         $user3 = self::getDataGenerator()->create_user();
2267         // The person asking for the messages for another user.
2268         $this->setUser($user1);
2270         // Ensure an exception is thrown.
2271         $this->expectException('moodle_exception');
2272         core_message_external::data_for_messagearea_messages($user2->id, $user3->id);
2273     }
2275     /**
2276      * Tests retrieving messages with messaging disabled.
2277      */
2278     public function test_messagearea_messages_messaging_disabled() {
2279         global $CFG;
2281         $this->resetAfterTest(true);
2283         // Create some skeleton data just so we can call the WS.
2284         $user1 = self::getDataGenerator()->create_user();
2285         $user2 = self::getDataGenerator()->create_user();
2287         // The person asking for the messages for another user.
2288         $this->setUser($user1);
2290         // Disable messaging.
2291         $CFG->messaging = 0;
2293         // Ensure an exception is thrown.
2294         $this->expectException('moodle_exception');
2295         core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2296     }
2298     /**
2299      * Tests retrieving most recent message.
2300      */
2301     public function test_messagearea_get_most_recent_message() {
2302         $this->resetAfterTest(true);
2304         // Create some users.
2305         $user1 = self::getDataGenerator()->create_user();
2306         $user2 = self::getDataGenerator()->create_user();
2308         // The person doing the search.
2309         $this->setUser($user1);
2311         // Send some messages back and forth.
2312         $time = time();
2313         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2314         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2315         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2316         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2318         // Get the most recent message.
2319         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
2321         // We need to execute the return values cleaning process to simulate the web service server.
2322         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
2323             $result);
2325         // Check the results are correct.
2326         $this->assertEquals($user2->id, $result['useridfrom']);
2327         $this->assertEquals($user1->id, $result['useridto']);
2328         $this->assertContains('Word.', $result['text']);
2329     }
2331     /**
2332      * Tests retrieving most recent message as another user.
2333      */
2334     public function test_messagearea_get_most_recent_message_as_other_user() {
2335         $this->resetAfterTest(true);
2337         // The person doing the search.
2338         $this->setAdminUser();
2340         // Create some users.
2341         $user1 = self::getDataGenerator()->create_user();
2342         $user2 = self::getDataGenerator()->create_user();
2344         // Send some messages back and forth.
2345         $time = time();
2346         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2347         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2348         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2349         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2351         // Get the most recent message.
2352         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
2354         // We need to execute the return values cleaning process to simulate the web service server.
2355         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
2356             $result);
2358         // Check the results are correct.
2359         $this->assertEquals($user2->id, $result['useridfrom']);
2360         $this->assertEquals($user1->id, $result['useridto']);
2361         $this->assertContains('Word.', $result['text']);
2362     }
2364     /**
2365      * Tests retrieving most recent message as another user without the proper capabilities.
2366      */
2367     public function test_messagearea_get_most_recent_message_as_other_user_without_cap() {
2368         $this->resetAfterTest(true);
2370         // Create some users.
2371         $user1 = self::getDataGenerator()->create_user();
2372         $user2 = self::getDataGenerator()->create_user();
2373         $user3 = self::getDataGenerator()->create_user();
2375         // The person asking for the most recent message for another user.
2376         $this->setUser($user1);
2378         // Ensure an exception is thrown.
2379         $this->expectException('moodle_exception');
2380         core_message_external::data_for_messagearea_get_most_recent_message($user2->id, $user3->id);
2381     }
2383     /**
2384      * Tests retrieving most recent message with messaging disabled.
2385      */
2386     public function test_messagearea_get_most_recent_message_messaging_disabled() {
2387         global $CFG;
2389         $this->resetAfterTest(true);
2391         // Create some skeleton data just so we can call the WS.
2392         $user1 = self::getDataGenerator()->create_user();
2393         $user2 = self::getDataGenerator()->create_user();
2395         // The person asking for the most recent message.
2396         $this->setUser($user1);
2398         // Disable messaging.
2399         $CFG->messaging = 0;
2401         // Ensure an exception is thrown.
2402         $this->expectException('moodle_exception');
2403         core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
2404     }
2406     /**
2407      * Tests retrieving a user's profile.
2408      */
2409     public function test_messagearea_get_profile() {
2410         $this->resetAfterTest(true);
2412         // Create some users.
2413         $user1 = self::getDataGenerator()->create_user();
2414         $user2 = self::getDataGenerator()->create_user();
2416         // The person asking for the profile information.
2417         $this->setUser($user1);
2419         // Get the profile.
2420         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
2422         // We need to execute the return values cleaning process to simulate the web service server.
2423         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_profile_returns(),
2424             $result);
2426         $this->assertEquals($user2->id, $result['userid']);
2427         $this->assertEmpty($result['email']);
2428         $this->assertEmpty($result['country']);
2429         $this->assertEmpty($result['city']);
2430         $this->assertEquals(fullname($user2), $result['fullname']);
2431         $this->assertNull($result['isonline']);
2432         $this->assertFalse($result['isblocked']);
2433         $this->assertFalse($result['iscontact']);
2434     }
2436     /**
2437      * Tests retrieving a user's profile as another user.
2438      */
2439     public function test_messagearea_profile_as_other_user() {
2440         $this->resetAfterTest(true);
2442         // The person asking for the profile information.
2443         $this->setAdminUser();
2445         // Create some users.
2446         $user1 = self::getDataGenerator()->create_user();
2448         $user2 = new stdClass();
2449         $user2->country = 'AU';
2450         $user2->city = 'Perth';
2451         $user2 = self::getDataGenerator()->create_user($user2);
2453         // Get the profile.
2454         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
2456         // We need to execute the return values cleaning process to simulate the web service server.
2457         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_profile_returns(),
2458             $result);
2460         $this->assertEquals($user2->id, $result['userid']);
2461         $this->assertEquals($user2->email, $result['email']);
2462         $this->assertEquals(get_string($user2->country, 'countries'), $result['country']);
2463         $this->assertEquals($user2->city, $result['city']);
2464         $this->assertEquals(fullname($user2), $result['fullname']);
2465         $this->assertFalse($result['isonline']);
2466         $this->assertFalse($result['isblocked']);
2467         $this->assertFalse($result['iscontact']);
2468     }
2470     /**
2471      * Tests retrieving a user's profile as another user without the proper capabilities.
2472      */
2473     public function test_messagearea_profile_as_other_user_without_cap() {
2474         $this->resetAfterTest(true);
2476         // Create some users.
2477         $user1 = self::getDataGenerator()->create_user();
2478         $user2 = self::getDataGenerator()->create_user();
2479         $user3 = self::getDataGenerator()->create_user();
2481         // The person asking for the profile information for another user.
2482         $this->setUser($user1);
2484         // Ensure an exception is thrown.
2485         $this->expectException('moodle_exception');
2486         core_message_external::data_for_messagearea_get_profile($user2->id, $user3->id);
2487     }
2489     /**
2490      * Tests retrieving a user's profile with messaging disabled.
2491      */
2492     public function test_messagearea_profile_messaging_disabled() {
2493         global $CFG;
2495         $this->resetAfterTest(true);
2497         // Create some skeleton data just so we can call the WS.
2498         $user1 = self::getDataGenerator()->create_user();
2499         $user2 = self::getDataGenerator()->create_user();
2501         // The person asking for the profile information.
2502         $this->setUser($user1);
2504         // Disable messaging.
2505         $CFG->messaging = 0;
2507         // Ensure an exception is thrown.
2508         $this->expectException('moodle_exception');
2509         core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
2510     }
2512     /**
2513      * Test marking all message as read with an invalid user.
2514      */
2515     public function test_mark_all_messages_as_read_invalid_user_exception() {
2516         $this->resetAfterTest(true);
2518         $this->expectException('moodle_exception');
2519         core_message_external::mark_all_messages_as_read(-2132131, 0);
2520     }
2522     /**
2523      * Test marking all message as read without proper access.
2524      */
2525     public function test_mark_all_messages_as_read_access_denied_exception() {
2526         $this->resetAfterTest(true);
2528         $sender = $this->getDataGenerator()->create_user();
2529         $user = $this->getDataGenerator()->create_user();
2531         $this->setUser($user);
2532         $this->expectException('moodle_exception');
2533         core_message_external::mark_all_messages_as_read($sender->id, 0);
2534     }
2536     /**
2537      * Test marking all message as read with missing from user.
2538      */
2539     public function test_mark_all_messages_as_read_missing_from_user_exception() {
2540         $this->resetAfterTest(true);
2542         $sender = $this->getDataGenerator()->create_user();
2544         $this->setUser($sender);
2545         $this->expectException('moodle_exception');
2546         core_message_external::mark_all_messages_as_read($sender->id, 99999);
2547     }
2549     /**
2550      * Test marking all message as read.
2551      */
2552     public function test_mark_all_messages_as_read() {
2553         global $DB;
2555         $this->resetAfterTest(true);
2557         $sender1 = $this->getDataGenerator()->create_user();
2558         $sender2 = $this->getDataGenerator()->create_user();
2559         $sender3 = $this->getDataGenerator()->create_user();
2560         $recipient = $this->getDataGenerator()->create_user();
2562         $this->setUser($recipient);
2564         $this->send_message($sender1, $recipient, 'Message');
2565         $this->send_message($sender1, $recipient, 'Message');
2566         $this->send_message($sender2, $recipient, 'Message');
2567         $this->send_message($sender2, $recipient, 'Message');
2568         $this->send_message($sender3, $recipient, 'Message');
2569         $this->send_message($sender3, $recipient, 'Message');
2571         core_message_external::mark_all_messages_as_read($recipient->id, $sender1->id);
2572         $this->assertEquals(2, $DB->count_records('message_user_actions'));
2574         core_message_external::mark_all_messages_as_read($recipient->id, 0);
2575         $this->assertEquals(6, $DB->count_records('message_user_actions'));
2576     }
2578     /**
2579      * Test getting unread conversation count.
2580      */
2581     public function test_get_unread_conversations_count() {
2582         $this->resetAfterTest(true);
2584         // Create some users.
2585         $user1 = self::getDataGenerator()->create_user();
2586         $user2 = self::getDataGenerator()->create_user();
2587         $user3 = self::getDataGenerator()->create_user();
2588         $user4 = self::getDataGenerator()->create_user();
2590         // The person wanting the conversation count.
2591         $this->setUser($user1);
2593         // Send some messages back and forth, have some different conversations with different users.
2594         $this->send_message($user1, $user2, 'Yo!');
2595         $this->send_message($user2, $user1, 'Sup mang?');
2596         $this->send_message($user1, $user2, 'Writing PHPUnit tests!');
2597         $this->send_message($user2, $user1, 'Word.');
2599         $this->send_message($user1, $user3, 'Booyah');
2600         $this->send_message($user3, $user1, 'Whaaat?');
2601         $this->send_message($user1, $user3, 'Nothing.');
2602         $this->send_message($user3, $user1, 'Cool.');
2604         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
2605         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
2606         $this->send_message($user1, $user4, 'Dope.');
2608         // Get the unread conversation count.
2609         $result = core_message_external::get_unread_conversations_count($user1->id);
2611         // We need to execute the return values cleaning process to simulate the web service server.
2612         $result = external_api::clean_returnvalue(core_message_external::get_unread_conversations_count_returns(),
2613             $result);
2615         $this->assertEquals(3, $result);
2616     }
2618     /**
2619      * Test getting unread conversation count as other user.
2620      */
2621     public function test_get_unread_conversations_count_as_other_user() {
2622         $this->resetAfterTest(true);
2624         // The person wanting the conversation count.
2625         $this->setAdminUser();
2627         // Create some users.
2628         $user1 = self::getDataGenerator()->create_user();
2629         $user2 = self::getDataGenerator()->create_user();
2630         $user3 = self::getDataGenerator()->create_user();
2631         $user4 = self::getDataGenerator()->create_user();
2633         // Send some messages back and forth, have some different conversations with different users.
2634         $this->send_message($user1, $user2, 'Yo!');
2635         $this->send_message($user2, $user1, 'Sup mang?');
2636         $this->send_message($user1, $user2, 'Writing PHPUnit tests!');
2637         $this->send_message($user2, $user1, 'Word.');
2639         $this->send_message($user1, $user3, 'Booyah');
2640         $this->send_message($user3, $user1, 'Whaaat?');
2641         $this->send_message($user1, $user3, 'Nothing.');
2642         $this->send_message($user3, $user1, 'Cool.');
2644         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
2645         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
2646         $this->send_message($user1, $user4, 'Dope.');
2648         // Get the unread conversation count.
2649         $result = core_message_external::get_unread_conversations_count($user1->id);
2651         // We need to execute the return values cleaning process to simulate the web service server.
2652         $result = external_api::clean_returnvalue(core_message_external::get_unread_conversations_count_returns(),
2653             $result);
2655         $this->assertEquals(3, $result);
2656     }
2658     /**
2659      * Test getting unread conversation count as other user without proper capability.
2660      */
2661     public function test_get_unread_conversations_count_as_other_user_without_cap() {
2662         $this->resetAfterTest(true);
2664         // Create some users.
2665         $user1 = self::getDataGenerator()->create_user();
2666         $user2 = self::getDataGenerator()->create_user();
2668         // The person wanting the conversation count.
2669         $this->setUser($user1);
2671         // Ensure an exception is thrown.
2672         $this->expectException('moodle_exception');
2673         core_message_external::get_unread_conversations_count($user2->id);
2674     }
2676     /**
2677      * Test deleting conversation.
2678      */
2679     public function test_delete_conversation() {
2680         global $DB;
2682         $this->resetAfterTest(true);
2684         // Create some users.
2685         $user1 = self::getDataGenerator()->create_user();
2686         $user2 = self::getDataGenerator()->create_user();
2688         // The person wanting to delete the conversation.
2689         $this->setUser($user1);
2691         // Send some messages back and forth.
2692         $time = time();
2693         $m1id = $this->send_message($user1, $user2, 'Yo!', 0, $time);
2694         $m2id = $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2695         $m3id = $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2696         $m4id = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2698         // Delete the conversation.
2699         core_message_external::delete_conversation($user1->id, $user2->id);
2701         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2702         $this->assertCount(4, $muas);
2703         // Sort by id.
2704         ksort($muas);
2706         $mua1 = array_shift($muas);
2707         $mua2 = array_shift($muas);
2708         $mua3 = array_shift($muas);
2709         $mua4 = array_shift($muas);
2711         $this->assertEquals($user1->id, $mua1->userid);
2712         $this->assertEquals($m1id, $mua1->messageid);
2713         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2715         $this->assertEquals($user1->id, $mua2->userid);
2716         $this->assertEquals($m2id, $mua2->messageid);
2717         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2719         $this->assertEquals($user1->id, $mua3->userid);
2720         $this->assertEquals($m3id, $mua3->messageid);
2721         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2723         $this->assertEquals($user1->id, $mua4->userid);
2724         $this->assertEquals($m4id, $mua4->messageid);
2725         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2726     }
2728     /**
2729      * Test deleting conversation as other user.
2730      */
2731     public function test_delete_conversation_as_other_user() {
2732         global $DB;
2734         $this->resetAfterTest(true);
2736         $this->setAdminUser();
2738         // Create some users.
2739         $user1 = self::getDataGenerator()->create_user();
2740         $user2 = self::getDataGenerator()->create_user();
2742         // Send some messages back and forth.
2743         $time = time();
2744         $m1id = $this->send_message($user1, $user2, 'Yo!', 0, $time);
2745         $m2id = $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2746         $m3id = $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2747         $m4id = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2749         // Delete the conversation.
2750         core_message_external::delete_conversation($user1->id, $user2->id);
2752         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2753         $this->assertCount(4, $muas);
2754         // Sort by id.
2755         ksort($muas);
2757         $mua1 = array_shift($muas);
2758         $mua2 = array_shift($muas);
2759         $mua3 = array_shift($muas);
2760         $mua4 = array_shift($muas);
2762         $this->assertEquals($user1->id, $mua1->userid);
2763         $this->assertEquals($m1id, $mua1->messageid);
2764         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2766         $this->assertEquals($user1->id, $mua2->userid);
2767         $this->assertEquals($m2id, $mua2->messageid);
2768         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2770         $this->assertEquals($user1->id, $mua3->userid);
2771         $this->assertEquals($m3id, $mua3->messageid);
2772         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2774         $this->assertEquals($user1->id, $mua4->userid);
2775         $this->assertEquals($m4id, $mua4->messageid);
2776         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2777     }
2779     /**
2780      * Test deleting conversation as other user without proper capability.
2781      */
2782     public function test_delete_conversation_as_other_user_without_cap() {
2783         $this->resetAfterTest(true);
2785         // Create some users.
2786         $user1 = self::getDataGenerator()->create_user();
2787         $user2 = self::getDataGenerator()->create_user();
2788         $user3 = self::getDataGenerator()->create_user();
2790         // The person wanting to delete the conversation.
2791         $this->setUser($user3);
2793         // Ensure an exception is thrown.
2794         $this->expectException('moodle_exception');
2795         core_message_external::delete_conversation($user1->id, $user2->id);
2796     }
2798     /**
2799      * Test deleting conversation with messaging disabled.
2800      */
2801     public function test_delete_conversation_messaging_disabled() {
2802         global $CFG;
2804         $this->resetAfterTest(true);
2806         // Create some users.
2807         $user1 = self::getDataGenerator()->create_user();
2808         $user2 = self::getDataGenerator()->create_user();
2810         // The person wanting to delete the conversation.
2811         $this->setUser($user1);
2813         // Disable messaging.
2814         $CFG->messaging = 0;
2816         // Ensure an exception is thrown.
2817         $this->expectException('moodle_exception');
2818         core_message_external::delete_conversation($user1->id, $user2->id);
2819     }
2821     /**
2822      * Test get message processor.
2823      */
2824     public function test_get_message_processor() {
2825         $this->resetAfterTest(true);
2827         // Create a user.
2828         $user1 = self::getDataGenerator()->create_user();
2830         // Set you as the user.
2831         $this->setUser($user1);
2833         // Get the message processors.
2834         $result = core_message_external::get_message_processor($user1->id, 'popup');
2836         // We need to execute the return values cleaning process to simulate the web service server.
2837         $result = external_api::clean_returnvalue(core_message_external::get_message_processor_returns(), $result);
2839         $this->assertNotEmpty($result['systemconfigured']);
2840         $this->assertNotEmpty($result['userconfigured']);
2841     }
2843     /**
2844      * Test get_user_notification_preferences
2845      */
2846     public function test_get_user_message_preferences() {
2847         $this->resetAfterTest(true);
2849         $user = self::getDataGenerator()->create_user();
2850         $this->setUser($user);
2852         // Set a couple of preferences to test.
2853         set_user_preference('message_provider_moodle_instantmessage_loggedin', 'email', $user);
2854         set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'email', $user);
2855         set_user_preference('message_blocknoncontacts', 1, $user);
2857         $prefs = core_message_external::get_user_message_preferences();
2858         $prefs = external_api::clean_returnvalue(core_message_external::get_user_message_preferences_returns(), $prefs);
2859         $this->assertEquals($user->id, $prefs['preferences']['userid']);
2861         // Check components.
2862         $this->assertCount(1, $prefs['preferences']['components']);
2863         $this->assertTrue($prefs['blocknoncontacts']);
2865         // Check some preferences that we previously set.
2866         $found = false;
2867         foreach ($prefs['preferences']['components'] as $component) {
2868             foreach ($component['notifications'] as $prefdata) {
2869                 if ($prefdata['preferencekey'] != 'message_provider_moodle_instantmessage') {
2870                     continue;
2871                 }
2872                 foreach ($prefdata['processors'] as $processor) {
2873                     if ($processor['name'] == 'email') {
2874                         $this->assertTrue($processor['loggedin']['checked']);
2875                         $this->assertTrue($processor['loggedoff']['checked']);
2876                         $found = true;
2877                     }
2878                 }
2879             }
2880         }
2881         $this->assertTrue($found);
2882     }
2884     /**
2885      * Test get_user_message_preferences permissions
2886      */
2887     public function test_get_user_message_preferences_permissions() {
2888         $this->resetAfterTest(true);
2890         $user = self::getDataGenerator()->create_user();
2891         $otheruser = self::getDataGenerator()->create_user();
2892         $this->setUser($user);
2894         $this->expectException('moodle_exception');
2895         $prefs = core_message_external::get_user_message_preferences($otheruser->id);
2896     }