MDL-63211 core_message: added new web services
[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 getting contact requests.
334      */
335     public function test_get_contact_requests() {
336         $this->resetAfterTest();
338         $user1 = self::getDataGenerator()->create_user();
339         $user2 = self::getDataGenerator()->create_user();
340         $user3 = self::getDataGenerator()->create_user();
342         $this->setUser($user1);
344         // Block one user, their request should not show up.
345         \core_message\api::block_user($user1->id, $user3->id);
347         \core_message\api::create_contact_request($user2->id, $user1->id);
348         \core_message\api::create_contact_request($user3->id, $user1->id);
350         $requests = core_message_external::get_contact_requests($user1->id);
351         $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
353         $this->assertCount(1, $requests);
355         $request = reset($requests);
357         $this->assertEquals($user2->id, $request['id']);
358         $this->assertEquals($user2->picture, $request['picture']);
359         $this->assertEquals($user2->firstname, $request['firstname']);
360         $this->assertEquals($user2->lastname, $request['lastname']);
361         $this->assertEquals($user2->firstnamephonetic, $request['firstnamephonetic']);
362         $this->assertEquals($user2->lastnamephonetic, $request['lastnamephonetic']);
363         $this->assertEquals($user2->middlename, $request['middlename']);
364         $this->assertEquals($user2->alternatename, $request['alternatename']);
365         $this->assertEquals($user2->email, $request['email']);
366     }
368     /**
369      * Test getting contact requests with messaging disabled.
370      */
371     public function test_get_contact_requests_messaging_disabled() {
372         global $CFG;
374         $this->resetAfterTest();
376         // Create some skeleton data just so we can call the WS.
377         $user1 = self::getDataGenerator()->create_user();
379         $this->setUser($user1);
381         // Disable messaging.
382         $CFG->messaging = 0;
384         // Ensure an exception is thrown.
385         $this->expectException('moodle_exception');
386         core_message_external::get_contact_requests($user1->id);
387     }
389     /**
390      * Test getting contact requests with no permission.
391      */
392     public function test_get_contact_requests_no_permission() {
393         $this->resetAfterTest();
395         // Create some skeleton data just so we can call the WS.
396         $user1 = self::getDataGenerator()->create_user();
397         $user2 = self::getDataGenerator()->create_user();
398         $user3 = self::getDataGenerator()->create_user();
400         $this->setUser($user3);
402         // Ensure an exception is thrown.
403         $this->expectException('required_capability_exception');
404         core_message_external::create_contact_request($user1->id, $user2->id);
405     }
407     /**
408      * Test creating a contact request.
409      */
410     public function test_create_contact_request() {
411         global $DB;
413         $this->resetAfterTest();
415         $user1 = self::getDataGenerator()->create_user();
416         $user2 = self::getDataGenerator()->create_user();
418         $this->setUser($user1);
420         $return = core_message_external::create_contact_request($user1->id, $user2->id);
421         $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
422         $this->assertEquals(array(), $return);
424         $request = $DB->get_records('message_contact_requests');
426         $this->assertCount(1, $request);
428         $request = reset($request);
430         $this->assertEquals($user1->id, $request->userid);
431         $this->assertEquals($user2->id, $request->requesteduserid);
432     }
434     /**
435      * Test creating a contact request with messaging disabled.
436      */
437     public function test_create_contact_request_messaging_disabled() {
438         global $CFG;
440         $this->resetAfterTest();
442         // Create some skeleton data just so we can call the WS.
443         $user1 = self::getDataGenerator()->create_user();
444         $user2 = self::getDataGenerator()->create_user();
446         $this->setUser($user1);
448         // Disable messaging.
449         $CFG->messaging = 0;
451         // Ensure an exception is thrown.
452         $this->expectException('moodle_exception');
453         core_message_external::create_contact_request($user1->id, $user2->id);
454     }
456     /**
457      * Test creating a contact request with no permission.
458      */
459     public function test_create_contact_request_no_permission() {
460         $this->resetAfterTest();
462         // Create some skeleton data just so we can call the WS.
463         $user1 = self::getDataGenerator()->create_user();
464         $user2 = self::getDataGenerator()->create_user();
465         $user3 = self::getDataGenerator()->create_user();
467         $this->setUser($user3);
469         // Ensure an exception is thrown.
470         $this->expectException('required_capability_exception');
471         core_message_external::create_contact_request($user1->id, $user2->id);
472     }
474     /**
475      * Test confirming a contact request.
476      */
477     public function test_confirm_contact_request() {
478         global $DB;
480         $this->resetAfterTest();
482         $user1 = self::getDataGenerator()->create_user();
483         $user2 = self::getDataGenerator()->create_user();
485         $this->setUser($user1);
487         \core_message\api::create_contact_request($user1->id, $user2->id);
489         $this->setUser($user2);
491         $return = core_message_external::confirm_contact_request($user1->id, $user2->id);
492         $return = external_api::clean_returnvalue(core_message_external::confirm_contact_request_returns(), $return);
493         $this->assertEquals(array(), $return);
495         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
497         $contact = $DB->get_records('message_contacts');
499         $this->assertCount(1, $contact);
501         $contact = reset($contact);
503         $this->assertEquals($user1->id, $contact->userid);
504         $this->assertEquals($user2->id, $contact->contactid);
505     }
507     /**
508      * Test confirming a contact request with messaging disabled.
509      */
510     public function test_confirm_contact_request_messaging_disabled() {
511         global $CFG;
513         $this->resetAfterTest();
515         // Create some skeleton data just so we can call the WS.
516         $user1 = self::getDataGenerator()->create_user();
517         $user2 = self::getDataGenerator()->create_user();
519         $this->setUser($user1);
521         // Disable messaging.
522         $CFG->messaging = 0;
524         // Ensure an exception is thrown.
525         $this->expectException('moodle_exception');
526         core_message_external::confirm_contact_request($user1->id, $user2->id);
527     }
529     /**
530      * Test confirming a contact request with no permission.
531      */
532     public function test_confirm_contact_request_no_permission() {
533         $this->resetAfterTest();
535         // Create some skeleton data just so we can call the WS.
536         $user1 = self::getDataGenerator()->create_user();
537         $user2 = self::getDataGenerator()->create_user();
538         $user3 = self::getDataGenerator()->create_user();
540         $this->setUser($user3);
542         // Ensure an exception is thrown.
543         $this->expectException('required_capability_exception');
544         core_message_external::confirm_contact_request($user1->id, $user2->id);
545     }
547     /**
548      * Test declining a contact request.
549      */
550     public function test_decline_contact_request() {
551         global $DB;
553         $this->resetAfterTest();
555         $user1 = self::getDataGenerator()->create_user();
556         $user2 = self::getDataGenerator()->create_user();
558         $this->setUser($user1);
560         \core_message\api::create_contact_request($user1->id, $user2->id);
562         $this->setUser($user2);
564         $return = core_message_external::decline_contact_request($user1->id, $user2->id);
565         $return = external_api::clean_returnvalue(core_message_external::decline_contact_request_returns(), $return);
566         $this->assertEquals(array(), $return);
568         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
569         $this->assertEquals(0, $DB->count_records('message_contacts'));
570     }
572     /**
573      * Test declining a contact request with messaging disabled.
574      */
575     public function test_decline_contact_request_messaging_disabled() {
576         global $CFG;
578         $this->resetAfterTest();
580         // Create some skeleton data just so we can call the WS.
581         $user1 = self::getDataGenerator()->create_user();
582         $user2 = self::getDataGenerator()->create_user();
584         $this->setUser($user1);
586         // Disable messaging.
587         $CFG->messaging = 0;
589         // Ensure an exception is thrown.
590         $this->expectException('moodle_exception');
591         core_message_external::decline_contact_request($user1->id, $user2->id);
592     }
594     /**
595      * Test declining a contact request with no permission.
596      */
597     public function test_decline_contact_request_no_permission() {
598         $this->resetAfterTest();
600         // Create some skeleton data just so we can call the WS.
601         $user1 = self::getDataGenerator()->create_user();
602         $user2 = self::getDataGenerator()->create_user();
603         $user3 = self::getDataGenerator()->create_user();
605         $this->setUser($user3);
607         // Ensure an exception is thrown.
608         $this->expectException('required_capability_exception');
609         core_message_external::decline_contact_request($user1->id, $user2->id);
610     }
612     /**
613      * Test blocking a user.
614      */
615     public function test_block_user() {
616         global $DB;
618         $this->resetAfterTest(true);
620         $user1 = self::getDataGenerator()->create_user();
621         $user2 = self::getDataGenerator()->create_user();
623         $this->setUser($user1);
625         // Blocking a user.
626         $return = core_message_external::block_user($user1->id, $user2->id);
627         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
628         $this->assertEquals(array(), $return);
630         // Get list of blocked users.
631         $record = $DB->get_record('message_users_blocked', []);
633         $this->assertEquals($user1->id, $record->userid);
634         $this->assertEquals($user2->id, $record->blockeduserid);
636         // Blocking a user who is already blocked.
637         $return = core_message_external::block_user($user1->id, $user2->id);
638         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
639         $this->assertEquals(array(), $return);
641         $this->assertEquals(1, $DB->count_records('message_users_blocked'));
642     }
644     /**
645      * Test blocking a user with messaging disabled.
646      */
647     public function test_block_user_messaging_disabled() {
648         global $CFG;
650         $this->resetAfterTest();
652         // Create some skeleton data just so we can call the WS.
653         $user1 = self::getDataGenerator()->create_user();
654         $user2 = self::getDataGenerator()->create_user();
656         $this->setUser($user1);
658         // Disable messaging.
659         $CFG->messaging = 0;
661         // Ensure an exception is thrown.
662         $this->expectException('moodle_exception');
663         core_message_external::block_user($user1->id, $user2->id);
664     }
666     /**
667      * Test blocking a user with no permission.
668      */
669     public function test_block_user_no_permission() {
670         $this->resetAfterTest();
672         // Create some skeleton data just so we can call the WS.
673         $user1 = self::getDataGenerator()->create_user();
674         $user2 = self::getDataGenerator()->create_user();
675         $user3 = self::getDataGenerator()->create_user();
677         $this->setUser($user3);
679         // Ensure an exception is thrown.
680         $this->expectException('required_capability_exception');
681         core_message_external::block_user($user1->id, $user2->id);
682     }
684     /**
685      * Test unblocking a user.
686      */
687     public function test_unblock_user() {
688         global $DB;
690         $this->resetAfterTest(true);
692         $user1 = self::getDataGenerator()->create_user();
693         $user2 = self::getDataGenerator()->create_user();
695         $this->setUser($user1);
697         // Block the user.
698         \core_message\api::block_user($user1->id, $user2->id);
700         // Unblocking a user.
701         $return = core_message_external::unblock_user($user1->id, $user2->id);
702         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
703         $this->assertEquals(array(), $return);
705         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
707         // Unblocking a user who is already unblocked.
708         $return = core_message_external::unblock_user($user1->id, $user2->id);
709         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
710         $this->assertEquals(array(), $return);
712         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
713     }
715     /**
716      * Test unblocking a user with messaging disabled.
717      */
718     public function test_unblock_user_messaging_disabled() {
719         global $CFG;
721         $this->resetAfterTest();
723         // Create some skeleton data just so we can call the WS.
724         $user1 = self::getDataGenerator()->create_user();
725         $user2 = self::getDataGenerator()->create_user();
727         $this->setUser($user1);
729         // Disable messaging.
730         $CFG->messaging = 0;
732         // Ensure an exception is thrown.
733         $this->expectException('moodle_exception');
734         core_message_external::unblock_user($user1->id, $user2->id);
735     }
737     /**
738      * Test unblocking a user with no permission.
739      */
740     public function test_unblock_user_no_permission() {
741         $this->resetAfterTest();
743         // Create some skeleton data just so we can call the WS.
744         $user1 = self::getDataGenerator()->create_user();
745         $user2 = self::getDataGenerator()->create_user();
746         $user3 = self::getDataGenerator()->create_user();
748         $this->setUser($user3);
750         // Ensure an exception is thrown.
751         $this->expectException('required_capability_exception');
752         core_message_external::unblock_user($user1->id, $user2->id);
753     }
755     /**
756      * Test get_contacts.
757      */
758     public function test_get_contacts() {
759         $this->resetAfterTest(true);
761         $user1 = self::getDataGenerator()->create_user();
762         $user_stranger = self::getDataGenerator()->create_user();
763         $user_offline1 = self::getDataGenerator()->create_user();
764         $user_offline2 = self::getDataGenerator()->create_user();
765         $user_offline3 = self::getDataGenerator()->create_user();
766         $user_online = new stdClass();
767         $user_online->lastaccess = time();
768         $user_online = self::getDataGenerator()->create_user($user_online);
769         $user_blocked = self::getDataGenerator()->create_user();
770         $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
772         // Login as user1.
773         $this->setUser($user1);
774         $this->assertEquals(array(), core_message_external::create_contacts(
775             array($user_offline1->id, $user_offline2->id, $user_offline3->id, $user_online->id)));
777         // User_stranger sends a couple of messages to user1.
778         $this->send_message($user_stranger, $user1, 'Hello there!');
779         $this->send_message($user_stranger, $user1, 'How you goin?');
780         $this->send_message($user_stranger, $user1, 'Cya!');
781         $this->send_message($noreplyuser, $user1, 'I am not a real user');
783         // User_blocked sends a message to user1.
784         $this->send_message($user_blocked, $user1, 'Here, have some spam.');
786         // Retrieve the contacts of the user.
787         $this->setUser($user1);
788         $contacts = core_message_external::get_contacts();
789         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
790         $this->assertCount(3, $contacts['offline']);
791         $this->assertCount(1, $contacts['online']);
792         $this->assertCount(3, $contacts['strangers']);
793         core_message_external::block_contacts(array($user_blocked->id));
794         $contacts = core_message_external::get_contacts();
795         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
796         $this->assertCount(3, $contacts['offline']);
797         $this->assertCount(1, $contacts['online']);
798         $this->assertCount(2, $contacts['strangers']);
800         // Checking some of the fields returned.
801         $stranger = array_pop($contacts['strangers']);
803         $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
804         $this->assertEquals(1, $stranger['unread']);
806         // Check that deleted users are not returned.
807         delete_user($user_offline1);
808         delete_user($user_stranger);
809         delete_user($user_online);
810         $contacts = core_message_external::get_contacts();
811         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
812         $this->assertCount(2, $contacts['offline']);
813         $this->assertCount(0, $contacts['online']);
814         $this->assertCount(1, $contacts['strangers']);
815     }
817     /**
818      * Test search_contacts.
819      * @expectedException moodle_exception
820      */
821     public function test_search_contacts() {
822         global $DB;
823         $this->resetAfterTest(true);
825         $course1 = $this->getDataGenerator()->create_course();
826         $course2 = $this->getDataGenerator()->create_course();
828         $user1 = new stdClass();
829         $user1->firstname = 'X';
830         $user1->lastname = 'X';
831         $user1 = $this->getDataGenerator()->create_user($user1);
832         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
833         $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
835         $user2 = new stdClass();
836         $user2->firstname = 'Eric';
837         $user2->lastname = 'Cartman';
838         $user2 = self::getDataGenerator()->create_user($user2);
839         $user3 = new stdClass();
840         $user3->firstname = 'Stan';
841         $user3->lastname = 'Marsh';
842         $user3 = self::getDataGenerator()->create_user($user3);
843         self::getDataGenerator()->enrol_user($user3->id, $course1->id);
844         $user4 = new stdClass();
845         $user4->firstname = 'Kyle';
846         $user4->lastname = 'Broflovski';
847         $user4 = self::getDataGenerator()->create_user($user4);
848         $user5 = new stdClass();
849         $user5->firstname = 'Kenny';
850         $user5->lastname = 'McCormick';
851         $user5 = self::getDataGenerator()->create_user($user5);
852         self::getDataGenerator()->enrol_user($user5->id, $course2->id);
854         $this->setUser($user1);
856         $results = core_message_external::search_contacts('r');
857         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
858         $this->assertCount(5, $results); // Users 2 through 5 + admin
860         $results = core_message_external::search_contacts('r', true);
861         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
862         $this->assertCount(2, $results);
864         $results = core_message_external::search_contacts('Kyle', false);
865         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
866         $this->assertCount(1, $results);
867         $result = reset($results);
868         $this->assertEquals($user4->id, $result['id']);
870         $results = core_message_external::search_contacts('y', false);
871         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
872         $this->assertCount(2, $results);
874         $results = core_message_external::search_contacts('y', true);
875         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
876         $this->assertCount(1, $results);
877         $result = reset($results);
878         $this->assertEquals($user5->id, $result['id']);
880         // Empty query, will throw an exception.
881         $results = core_message_external::search_contacts('');
882     }
884     /**
885      * Test get_messages.
886      */
887     public function test_get_messages() {
888         global $CFG, $DB;
889         $this->resetAfterTest(true);
891         $this->preventResetByRollback();
892         // This mark the messages as read!.
893         $sink = $this->redirectMessages();
895         $user1 = self::getDataGenerator()->create_user();
896         $user2 = self::getDataGenerator()->create_user();
897         $user3 = self::getDataGenerator()->create_user();
899         $course = self::getDataGenerator()->create_course();
901         // Send a message from one user to another.
902         message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
903         message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
904         message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
905         message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
906         message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);
908         $this->setUser($user1);
909         // Get read conversations from user1 to user2.
910         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
911         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
912         $this->assertCount(1, $messages['messages']);
914         // Delete the message.
915         $message = array_shift($messages['messages']);
916         \core_message\api::delete_message($user1->id, $message['id']);
918         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
919         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
920         $this->assertCount(0, $messages['messages']);
922         // Get unread conversations from user1 to user2.
923         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
924         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
925         $this->assertCount(0, $messages['messages']);
927         // Get read messages send from user1.
928         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
929         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
930         $this->assertCount(1, $messages['messages']);
932         $this->setUser($user2);
933         // Get read conversations from any user to user2.
934         $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
935         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
936         $this->assertCount(2, $messages['messages']);
938         // Conversations from user3 to user2.
939         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
940         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
941         $this->assertCount(1, $messages['messages']);
943         // Delete the message.
944         $message = array_shift($messages['messages']);
945         \core_message\api::delete_message($user2->id, $message['id']);
947         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
948         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
949         $this->assertCount(0, $messages['messages']);
951         $this->setUser($user3);
952         // Get read notifications received by user3.
953         $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
954         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
955         $this->assertCount(0, $messages['messages']);
957         // Now, create some notifications...
958         // We are creating fake notifications but based on real ones.
960         // This one comes from a disabled plugin's provider and therefore is not sent.
961         $eventdata = new \core\message\message();
962         $eventdata->courseid          = $course->id;
963         $eventdata->notification      = 1;
964         $eventdata->modulename        = 'moodle';
965         $eventdata->component         = 'enrol_paypal';
966         $eventdata->name              = 'paypal_enrolment';
967         $eventdata->userfrom          = get_admin();
968         $eventdata->userto            = $user1;
969         $eventdata->subject           = "Moodle: PayPal payment";
970         $eventdata->fullmessage       = "Your PayPal payment is pending.";
971         $eventdata->fullmessageformat = FORMAT_PLAIN;
972         $eventdata->fullmessagehtml   = '';
973         $eventdata->smallmessage      = '';
974         message_send($eventdata);
975         $this->assertDebuggingCalled('Attempt to send msg from a provider enrol_paypal/paypal_enrolment '.
976             'that is inactive or not allowed for the user id='.$user1->id);
978         // This one omits notification = 1.
979         $message = new \core\message\message();
980         $message->courseid          = $course->id;
981         $message->component         = 'enrol_manual';
982         $message->name              = 'expiry_notification';
983         $message->userfrom          = $user2;
984         $message->userto            = $user1;
985         $message->subject           = 'Test: This is not a notification but otherwise is valid';
986         $message->fullmessage       = 'Test: Full message';
987         $message->fullmessageformat = FORMAT_MARKDOWN;
988         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
989         $message->smallmessage      = $message->subject;
990         $message->contexturlname    = $course->fullname;
991         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
992         message_send($message);
994         $message = new \core\message\message();
995         $message->courseid          = $course->id;
996         $message->notification      = 1;
997         $message->component         = 'enrol_manual';
998         $message->name              = 'expiry_notification';
999         $message->userfrom          = $user2;
1000         $message->userto            = $user1;
1001         $message->subject           = 'Enrolment expired';
1002         $message->fullmessage       = 'Enrolment expired blah blah blah';
1003         $message->fullmessageformat = FORMAT_MARKDOWN;
1004         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
1005         $message->smallmessage      = $message->subject;
1006         $message->contexturlname    = $course->fullname;
1007         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1008         message_send($message);
1010         $userfrom = core_user::get_noreply_user();
1011         $userfrom->maildisplay = true;
1012         $eventdata = new \core\message\message();
1013         $eventdata->courseid          = $course->id;
1014         $eventdata->component         = 'moodle';
1015         $eventdata->name              = 'badgecreatornotice';
1016         $eventdata->userfrom          = $userfrom;
1017         $eventdata->userto            = $user1;
1018         $eventdata->notification      = 1;
1019         $eventdata->subject           = 'New badge';
1020         $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
1021         $eventdata->fullmessageformat = FORMAT_PLAIN;
1022         $eventdata->fullmessagehtml   = $eventdata->subject;
1023         $eventdata->smallmessage      = $eventdata->subject;
1024         message_send($eventdata);
1026         $eventdata = new \core\message\message();
1027         $eventdata->courseid         = $course->id;
1028         $eventdata->name             = 'submission';
1029         $eventdata->component        = 'mod_feedback';
1030         $eventdata->userfrom         = $user1;
1031         $eventdata->userto           = $user2;
1032         $eventdata->subject          = 'Feedback submitted';
1033         $eventdata->fullmessage      = 'Feedback submitted from an user';
1034         $eventdata->fullmessageformat = FORMAT_PLAIN;
1035         $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
1036         $eventdata->smallmessage     = '';
1037         message_send($eventdata);
1039         $this->setUser($user1);
1040         // Get read notifications from any user to user1.
1041         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
1042         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1043         $this->assertCount(3, $messages['messages']);
1045         // Get one read notifications from any user to user1.
1046         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
1047         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1048         $this->assertCount(1, $messages['messages']);
1050         // Get unread notifications from any user to user1.
1051         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
1052         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1053         $this->assertCount(0, $messages['messages']);
1055         // Get read both type of messages from any user to user1.
1056         $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
1057         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1058         $this->assertCount(4, $messages['messages']);
1060         // Get read notifications from no-reply-user to user1.
1061         $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
1062         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1063         $this->assertCount(1, $messages['messages']);
1065         // Get notifications send by user1 to any user.
1066         $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
1067         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1068         $this->assertCount(1, $messages['messages']);
1070         // Test warnings.
1071         $CFG->messaging = 0;
1073         $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
1074         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1075         $this->assertCount(1, $messages['warnings']);
1077         // Test exceptions.
1079         // Messaging disabled.
1080         try {
1081             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1082             $this->fail('Exception expected due messaging disabled.');
1083         } catch (moodle_exception $e) {
1084             $this->assertEquals('disabled', $e->errorcode);
1085         }
1087         $CFG->messaging = 1;
1089         // Invalid users.
1090         try {
1091             $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
1092             $this->fail('Exception expected due invalid users.');
1093         } catch (moodle_exception $e) {
1094             $this->assertEquals('accessdenied', $e->errorcode);
1095         }
1097         // Invalid user ids.
1098         try {
1099             $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
1100             $this->fail('Exception expected due invalid users.');
1101         } catch (moodle_exception $e) {
1102             $this->assertEquals('invaliduser', $e->errorcode);
1103         }
1105         // Invalid users (permissions).
1106         $this->setUser($user2);
1107         try {
1108             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1109             $this->fail('Exception expected due invalid user.');
1110         } catch (moodle_exception $e) {
1111             $this->assertEquals('accessdenied', $e->errorcode);
1112         }
1114     }
1116     /**
1117      * Test get_messages where we want all messages from a user, sent to any user.
1118      */
1119     public function test_get_messages_useridto_all() {
1120         $this->resetAfterTest(true);
1122         $user1 = self::getDataGenerator()->create_user();
1123         $user2 = self::getDataGenerator()->create_user();
1124         $user3 = self::getDataGenerator()->create_user();
1126         $this->setUser($user1);
1128         // Send a message from user 1 to two other users.
1129         $this->send_message($user1, $user2, 'some random text 1', 0, 1);
1130         $this->send_message($user1, $user3, 'some random text 2', 0, 2);
1132         // Get messages sent from user 1.
1133         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', false, false, 0, 0);
1134         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1136         // Confirm the data is correct.
1137         $messages = $messages['messages'];
1138         $this->assertCount(2, $messages);
1140         $message1 = array_shift($messages);
1141         $message2 = array_shift($messages);
1143         $this->assertEquals($user1->id, $message1['useridfrom']);
1144         $this->assertEquals($user2->id, $message1['useridto']);
1146         $this->assertEquals($user1->id, $message2['useridfrom']);
1147         $this->assertEquals($user3->id, $message2['useridto']);
1148     }
1150     /**
1151      * Test get_messages where we want all messages to a user, sent by any user.
1152      */
1153     public function test_get_messages_useridfrom_all() {
1154         $this->resetAfterTest();
1156         $user1 = self::getDataGenerator()->create_user();
1157         $user2 = self::getDataGenerator()->create_user();
1158         $user3 = self::getDataGenerator()->create_user();
1160         $this->setUser($user1);
1162         // Send a message to user 1 from two other users.
1163         $this->send_message($user2, $user1, 'some random text 1', 0, 1);
1164         $this->send_message($user3, $user1, 'some random text 2', 0, 2);
1166         // Get messages sent to user 1.
1167         $messages = core_message_external::get_messages($user1->id, 0, 'conversations', false, false, 0, 0);
1168         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1170         // Confirm the data is correct.
1171         $messages = $messages['messages'];
1172         $this->assertCount(2, $messages);
1174         $message1 = array_shift($messages);
1175         $message2 = array_shift($messages);
1177         $this->assertEquals($user2->id, $message1['useridfrom']);
1178         $this->assertEquals($user1->id, $message1['useridto']);
1180         $this->assertEquals($user3->id, $message2['useridfrom']);
1181         $this->assertEquals($user1->id, $message2['useridto']);
1182     }
1184     /**
1185      * Test get_blocked_users.
1186      */
1187     public function test_get_blocked_users() {
1188         $this->resetAfterTest(true);
1190         $user1 = self::getDataGenerator()->create_user();
1191         $userstranger = self::getDataGenerator()->create_user();
1192         $useroffline1 = self::getDataGenerator()->create_user();
1193         $useroffline2 = self::getDataGenerator()->create_user();
1194         $userblocked = self::getDataGenerator()->create_user();
1196         // Login as user1.
1197         $this->setUser($user1);
1198         $this->assertEquals(array(), core_message_external::create_contacts(
1199             array($useroffline1->id, $useroffline2->id)));
1201         // The userstranger sends a couple of messages to user1.
1202         $this->send_message($userstranger, $user1, 'Hello there!');
1203         $this->send_message($userstranger, $user1, 'How you goin?');
1205         // The userblocked sends a message to user1.
1206         // Note that this user is not blocked at this point.
1207         $this->send_message($userblocked, $user1, 'Here, have some spam.');
1209         // Retrieve the list of blocked users.
1210         $this->setUser($user1);
1211         $blockedusers = core_message_external::get_blocked_users($user1->id);
1212         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1213         $this->assertCount(0, $blockedusers['users']);
1215         // Block the $userblocked and retrieve again the list.
1216         core_message_external::block_contacts(array($userblocked->id));
1217         $blockedusers = core_message_external::get_blocked_users($user1->id);
1218         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1219         $this->assertCount(1, $blockedusers['users']);
1221         // Remove the $userblocked and check that the list now is empty.
1222         delete_user($userblocked);
1223         $blockedusers = core_message_external::get_blocked_users($user1->id);
1224         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1225         $this->assertCount(0, $blockedusers['users']);
1227     }
1229     /**
1230      * Test mark_message_read.
1231      */
1232     public function test_mark_message_read() {
1233         $this->resetAfterTest(true);
1235         $user1 = self::getDataGenerator()->create_user();
1236         $user2 = self::getDataGenerator()->create_user();
1237         $user3 = self::getDataGenerator()->create_user();
1239         // Login as user1.
1240         $this->setUser($user1);
1241         $this->assertEquals(array(), core_message_external::create_contacts(
1242             array($user2->id, $user3->id)));
1244         // The user2 sends a couple of messages to user1.
1245         $this->send_message($user2, $user1, 'Hello there!');
1246         $this->send_message($user2, $user1, 'How you goin?');
1247         $this->send_message($user3, $user1, 'How you goin?');
1248         $this->send_message($user3, $user2, 'How you goin?');
1250         // Retrieve all messages sent by user2 (they are currently unread).
1251         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1253         $messageids = array();
1254         foreach ($lastmessages as $m) {
1255             $messageid = core_message_external::mark_message_read($m->id, time());
1256             $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
1257         }
1259         // Retrieve all messages sent (they are currently read).
1260         $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
1261         $this->assertCount(2, $lastmessages);
1262         $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
1263         $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
1265         // Retrieve all messages sent by any user (that are currently unread).
1266         $lastmessages = message_get_messages($user1->id, 0, 0, false);
1267         $this->assertCount(1, $lastmessages);
1269         // Invalid message ids.
1270         try {
1271             $messageid = core_message_external::mark_message_read(1337, time());
1272             $this->fail('Exception expected due invalid messageid.');
1273         } catch (dml_missing_record_exception $e) {
1274             $this->assertEquals('invalidrecordunknown', $e->errorcode);
1275         }
1277         // A message to a different user.
1278         $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
1279         $messageid = array_pop($lastmessages)->id;
1280         try {
1281             $messageid = core_message_external::mark_message_read($messageid, time());
1282             $this->fail('Exception expected due invalid messageid.');
1283         } catch (invalid_parameter_exception $e) {
1284             $this->assertEquals('invalidparameter', $e->errorcode);
1285         }
1286     }
1288     /**
1289      * Test mark_notification_read.
1290      */
1291     public function test_mark_notification_read() {
1292         $this->resetAfterTest(true);
1294         $user1 = self::getDataGenerator()->create_user();
1295         $user2 = self::getDataGenerator()->create_user();
1296         $user3 = self::getDataGenerator()->create_user();
1298         // Login as user1.
1299         $this->setUser($user1);
1300         $this->assertEquals(array(), core_message_external::create_contacts(
1301             array($user2->id, $user3->id)));
1303         // The user2 sends a couple of notifications to user1.
1304         $this->send_message($user2, $user1, 'Hello there!', 1);
1305         $this->send_message($user2, $user1, 'How you goin?', 1);
1306         $this->send_message($user3, $user1, 'How you goin?', 1);
1307         $this->send_message($user3, $user2, 'How you goin?', 1);
1309         // Retrieve all notifications sent by user2 (they are currently unread).
1310         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, false);
1312         $notificationids = array();
1313         foreach ($lastnotifications as $n) {
1314             $notificationid = core_message_external::mark_notification_read($n->id, time());
1315             $notificationids[] = external_api::clean_returnvalue(core_message_external::mark_notification_read_returns(),
1316                 $notificationid);
1317         }
1319         // Retrieve all notifications sent (they are currently read).
1320         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, true);
1321         $this->assertCount(2, $lastnotifications);
1322         $this->assertArrayHasKey($notificationids[1]['notificationid'], $lastnotifications);
1323         $this->assertArrayHasKey($notificationids[0]['notificationid'], $lastnotifications);
1325         // Retrieve all notifications sent by any user (that are currently unread).
1326         $lastnotifications = message_get_messages($user1->id, 0, 1, false);
1327         $this->assertCount(1, $lastnotifications);
1329         // Invalid notification ids.
1330         try {
1331             $notificationid = core_message_external::mark_notification_read(1337, time());
1332             $this->fail('Exception expected due invalid notificationid.');
1333         } catch (dml_missing_record_exception $e) {
1334             $this->assertEquals('invalidrecord', $e->errorcode);
1335         }
1337         // A notification to a different user.
1338         $lastnotifications = message_get_messages($user2->id, $user3->id, 1, false);
1339         $notificationid = array_pop($lastnotifications)->id;
1340         try {
1341             $notificationid = core_message_external::mark_notification_read($notificationid, time());
1342             $this->fail('Exception expected due invalid notificationid.');
1343         } catch (invalid_parameter_exception $e) {
1344             $this->assertEquals('invalidparameter', $e->errorcode);
1345         }
1346     }
1348     /**
1349      * Test delete_message.
1350      */
1351     public function test_delete_message() {
1352         global $DB;
1353         $this->resetAfterTest(true);
1355         $user1 = self::getDataGenerator()->create_user();
1356         $user2 = self::getDataGenerator()->create_user();
1357         $user3 = self::getDataGenerator()->create_user();
1358         $user4 = self::getDataGenerator()->create_user();
1360         // Login as user1.
1361         $this->setUser($user1);
1362         $this->assertEquals(array(), core_message_external::create_contacts(array($user2->id, $user3->id)));
1364         // User user1 does not interchange messages with user3.
1365         $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1366         $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1367         $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1368         $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
1370         // Retrieve all messages sent by user2 (they are currently unread).
1371         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1373         // Delete a message not read, as a user from.
1374         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1375         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1376         $this->assertTrue($result['status']);
1377         $this->assertCount(0, $result['warnings']);
1378         $mua = $DB->get_record('message_user_actions', array('messageid' => $m1to2, 'userid' => $user1->id));
1379         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua->action);
1381         // Try to delete the same message again.
1382         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1383         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1384         $this->assertFalse($result['status']);
1386         // Try to delete a message that does not belong to me.
1387         try {
1388             $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
1389             $this->fail('Exception expected due invalid messageid.');
1390         } catch (moodle_exception $e) {
1391             $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
1392         }
1394         $this->setUser($user3);
1395         // Delete a message not read, as a user to.
1396         $result = core_message_external::delete_message($m2to3, $user3->id, false);
1397         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1398         $this->assertTrue($result['status']);
1399         $this->assertCount(0, $result['warnings']);
1400         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m2to3, 'userid' => $user3->id,
1401             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1403         // Delete a message read.
1404         $message = $DB->get_record('messages', ['id' => $m3to2]);
1405         \core_message\api::mark_message_as_read($user3->id, $message, time());
1406         $result = core_message_external::delete_message($m3to2, $user3->id);
1407         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1408         $this->assertTrue($result['status']);
1409         $this->assertCount(0, $result['warnings']);
1410         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to2, 'userid' => $user3->id,
1411             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1413         // Invalid message ids.
1414         try {
1415             $result = core_message_external::delete_message(-1, $user1->id);
1416             $this->fail('Exception expected due invalid messageid.');
1417         } catch (dml_missing_record_exception $e) {
1418             $this->assertEquals('invalidrecordunknown', $e->errorcode);
1419         }
1421         // Invalid user.
1422         try {
1423             $result = core_message_external::delete_message($m1to2, -1, false);
1424             $this->fail('Exception expected due invalid user.');
1425         } catch (moodle_exception $e) {
1426             $this->assertEquals('invaliduser', $e->errorcode);
1427         }
1429         // Not active user.
1430         delete_user($user2);
1431         try {
1432             $result = core_message_external::delete_message($m1to2, $user2->id, false);
1433             $this->fail('Exception expected due invalid user.');
1434         } catch (moodle_exception $e) {
1435             $this->assertEquals('userdeleted', $e->errorcode);
1436         }
1438         // Now, as an admin, try to delete any message.
1439         $this->setAdminUser();
1440         $result = core_message_external::delete_message($m3to4, $user4->id, false);
1441         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1442         $this->assertTrue($result['status']);
1443         $this->assertCount(0, $result['warnings']);
1444         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to4, 'userid' => $user4->id,
1445             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1447     }
1449     public function test_mark_all_notifications_as_read_invalid_user_exception() {
1450         $this->resetAfterTest(true);
1452         $this->expectException('moodle_exception');
1453         core_message_external::mark_all_notifications_as_read(-2132131, 0);
1454     }
1456     public function test_mark_all_notifications_as_read_access_denied_exception() {
1457         $this->resetAfterTest(true);
1459         $sender = $this->getDataGenerator()->create_user();
1460         $user = $this->getDataGenerator()->create_user();
1462         $this->setUser($user);
1463         $this->expectException('moodle_exception');
1464         core_message_external::mark_all_notifications_as_read($sender->id, 0);
1465     }
1467     public function test_mark_all_notifications_as_read_missing_from_user_exception() {
1468         $this->resetAfterTest(true);
1470         $sender = $this->getDataGenerator()->create_user();
1472         $this->setUser($sender);
1473         $this->expectException('moodle_exception');
1474         core_message_external::mark_all_notifications_as_read($sender->id, 99999);
1475     }
1477     public function test_mark_all_notifications_as_read() {
1478         global $DB;
1480         $this->resetAfterTest(true);
1482         $sender1 = $this->getDataGenerator()->create_user();
1483         $sender2 = $this->getDataGenerator()->create_user();
1484         $sender3 = $this->getDataGenerator()->create_user();
1485         $recipient = $this->getDataGenerator()->create_user();
1487         $this->setUser($recipient);
1489         $this->send_message($sender1, $recipient, 'Notification', 1);
1490         $this->send_message($sender1, $recipient, 'Notification', 1);
1491         $this->send_message($sender2, $recipient, 'Notification', 1);
1492         $this->send_message($sender2, $recipient, 'Notification', 1);
1493         $this->send_message($sender3, $recipient, 'Notification', 1);
1494         $this->send_message($sender3, $recipient, 'Notification', 1);
1496         core_message_external::mark_all_notifications_as_read($recipient->id, $sender1->id);
1497         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1498         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1500         $this->assertCount(2, $readnotifications);
1501         $this->assertCount(4, $unreadnotifications);
1503         core_message_external::mark_all_notifications_as_read($recipient->id, 0);
1504         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1505         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1507         $this->assertCount(6, $readnotifications);
1508         $this->assertCount(0, $unreadnotifications);
1509     }
1511     /**
1512      * Test get_user_notification_preferences
1513      */
1514     public function test_get_user_notification_preferences() {
1515         $this->resetAfterTest(true);
1517         $user = self::getDataGenerator()->create_user();
1518         $this->setUser($user);
1520         // Set a couple of preferences to test.
1521         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
1522         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
1524         $prefs = core_message_external::get_user_notification_preferences();
1525         $prefs = external_api::clean_returnvalue(core_message_external::get_user_notification_preferences_returns(), $prefs);
1526         // Check processors.
1527         $this->assertGreaterThanOrEqual(2, count($prefs['preferences']['processors']));
1528         $this->assertEquals($user->id, $prefs['preferences']['userid']);
1530         // Check components.
1531         $this->assertGreaterThanOrEqual(8, count($prefs['preferences']['components']));
1533         // Check some preferences that we previously set.
1534         $found = 0;
1535         foreach ($prefs['preferences']['components'] as $component) {
1536             foreach ($component['notifications'] as $prefdata) {
1537                 if ($prefdata['preferencekey'] != 'message_provider_mod_assign_assign_notification') {
1538                     continue;
1539                 }
1540                 foreach ($prefdata['processors'] as $processor) {
1541                     if ($processor['name'] == 'popup') {
1542                         $this->assertTrue($processor['loggedin']['checked']);
1543                         $found++;
1544                     } else if ($processor['name'] == 'email') {
1545                         $this->assertTrue($processor['loggedoff']['checked']);
1546                         $found++;
1547                     }
1548                 }
1549             }
1550         }
1551         $this->assertEquals(2, $found);
1552     }
1554     /**
1555      * Test get_user_notification_preferences permissions
1556      */
1557     public function test_get_user_notification_preferences_permissions() {
1558         $this->resetAfterTest(true);
1560         $user = self::getDataGenerator()->create_user();
1561         $otheruser = self::getDataGenerator()->create_user();
1562         $this->setUser($user);
1564         $this->expectException('moodle_exception');
1565         $prefs = core_message_external::get_user_notification_preferences($otheruser->id);
1566     }
1568     /**
1569      * Tests searching users in a course.
1570      */
1571     public function test_messagearea_search_users_in_course() {
1572         $this->resetAfterTest(true);
1574         // Create some users.
1575         $user1 = new stdClass();
1576         $user1->firstname = 'User';
1577         $user1->lastname = 'One';
1578         $user1 = self::getDataGenerator()->create_user($user1);
1580         // The person doing the search.
1581         $this->setUser($user1);
1583         // Set the second user's status to online by setting their last access to now.
1584         $user2 = new stdClass();
1585         $user2->firstname = 'User';
1586         $user2->lastname = 'Two';
1587         $user2->lastaccess = time();
1588         $user2 = self::getDataGenerator()->create_user($user2);
1590         // Block the second user.
1591         message_block_contact($user2->id, $user1->id);
1593         $user3 = new stdClass();
1594         $user3->firstname = 'User';
1595         $user3->lastname = 'Three';
1596         $user3 = self::getDataGenerator()->create_user($user3);
1598         // Create a course.
1599         $course1 = new stdClass();
1600         $course1->fullname = 'Course';
1601         $course1->shortname = 'One';
1602         $course1 = $this->getDataGenerator()->create_course();
1604         // Enrol the user we are doing the search for and one user in the course.
1605         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1606         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1608         // Perform a search.
1609         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1611         // We need to execute the return values cleaning process to simulate the web service.
1612         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1613             $result);
1615         // Check that we only retrieved a user that was enrolled, and that the user performing the search was not returned.
1616         $users = $result['contacts'];
1617         $this->assertCount(1, $users);
1619         $user = $users[0];
1620         $this->assertEquals($user2->id, $user['userid']);
1621         $this->assertEquals(fullname($user2), $user['fullname']);
1622         $this->assertFalse($user['ismessaging']);
1623         $this->assertFalse($user['sentfromcurrentuser']);
1624         $this->assertNull($user['lastmessage']);
1625         $this->assertNull($user['messageid']);
1626         $this->assertNull($user['isonline']);
1627         $this->assertFalse($user['isread']);
1628         $this->assertTrue($user['isblocked']);
1629         $this->assertNull($user['unreadcount']);
1630     }
1632     /**
1633      * Tests searching users in course as another user.
1634      */
1635     public function test_messagearea_search_users_in_course_as_other_user() {
1636         $this->resetAfterTest(true);
1638         // The person doing the search for another user.
1639         $this->setAdminUser();
1641         // Create some users.
1642         $user1 = new stdClass();
1643         $user1->firstname = 'User';
1644         $user1->lastname = 'One';
1645         $user1 = self::getDataGenerator()->create_user($user1);
1647         $user2 = new stdClass();
1648         $user2->firstname = 'User';
1649         $user2->lastname = 'Two';
1650         $user2 = self::getDataGenerator()->create_user($user2);
1652         $user3 = new stdClass();
1653         $user3->firstname = 'User';
1654         $user3->lastname = 'Three';
1655         $user3 = self::getDataGenerator()->create_user($user3);
1657         // Create a course.
1658         $course1 = new stdClass();
1659         $course1->fullname = 'Course';
1660         $course1->shortname = 'One';
1661         $course1 = $this->getDataGenerator()->create_course();
1663         // Enrol the user we are doing the search for and one user in the course.
1664         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1665         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1667         // Perform a search.
1668         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1670         // We need to execute the return values cleaning process to simulate the web service server.
1671         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1672             $result);
1674         // Check that we got the user enrolled, and that the user we are performing the search on behalf of was not returned.
1675         $users = $result['contacts'];
1676         $this->assertCount(1, $users);
1678         $user = $users[0];
1679         $this->assertEquals($user2->id, $user['userid']);
1680         $this->assertEquals(fullname($user2), $user['fullname']);
1681         $this->assertFalse($user['ismessaging']);
1682         $this->assertFalse($user['sentfromcurrentuser']);
1683         $this->assertNull($user['lastmessage']);
1684         $this->assertNull($user['messageid']);
1685         $this->assertFalse($user['isonline']);
1686         $this->assertFalse($user['isread']);
1687         $this->assertFalse($user['isblocked']);
1688         $this->assertNull($user['unreadcount']);
1689     }
1691     /**
1692      * Tests searching users in course as another user without the proper capabilities.
1693      */
1694     public function test_messagearea_search_users_in_course_as_other_user_without_cap() {
1695         $this->resetAfterTest(true);
1697         // Create some users.
1698         $user1 = self::getDataGenerator()->create_user();
1699         $user2 = self::getDataGenerator()->create_user();
1701         // The person doing the search for another user.
1702         $this->setUser($user1);
1704         // Create a course.
1705         $course = $this->getDataGenerator()->create_course();
1707         // Ensure an exception is thrown.
1708         $this->expectException('moodle_exception');
1709         core_message_external::data_for_messagearea_search_users_in_course($user2->id, $course->id, 'User');
1710     }
1712     /**
1713      * Tests searching users in course with messaging disabled.
1714      */
1715     public function test_messagearea_search_users_in_course_messaging_disabled() {
1716         global $CFG;
1718         $this->resetAfterTest(true);
1720         // Create some skeleton data just so we can call the WS..
1721         $user = self::getDataGenerator()->create_user();
1722         $course = $this->getDataGenerator()->create_course();
1724         // The person doing the search for another user.
1725         $this->setUser($user);
1727         // Disable messaging.
1728         $CFG->messaging = 0;
1730         // Ensure an exception is thrown.
1731         $this->expectException('moodle_exception');
1732         core_message_external::data_for_messagearea_search_users_in_course($user->id, $course->id, 'User');
1733     }
1735     /**
1736      * Tests searching users.
1737      */
1738     public function test_messagearea_search_users() {
1739         $this->resetAfterTest(true);
1741         // Create some users.
1742         $user1 = new stdClass();
1743         $user1->firstname = 'User';
1744         $user1->lastname = 'One';
1745         $user1 = self::getDataGenerator()->create_user($user1);
1747         // Set as the user performing the search.
1748         $this->setUser($user1);
1750         $user2 = new stdClass();
1751         $user2->firstname = 'User search';
1752         $user2->lastname = 'Two';
1753         $user2 = self::getDataGenerator()->create_user($user2);
1755         $user3 = new stdClass();
1756         $user3->firstname = 'User search';
1757         $user3->lastname = 'Three';
1758         $user3 = self::getDataGenerator()->create_user($user3);
1760         $user4 = new stdClass();
1761         $user4->firstname = 'User';
1762         $user4->lastname = 'Four';
1763         $user4 = self::getDataGenerator()->create_user($user4);
1765         $user5 = new stdClass();
1766         $user5->firstname = 'User search';
1767         $user5->lastname = 'Five';
1768         $user5 = self::getDataGenerator()->create_user($user5);
1770         $user6 = new stdClass();
1771         $user6->firstname = 'User';
1772         $user6->lastname = 'Six';
1773         $user6 = self::getDataGenerator()->create_user($user6);
1775         // Create some courses.
1776         $course1 = new stdClass();
1777         $course1->fullname = 'Course search';
1778         $course1->shortname = 'One';
1779         $course1 = $this->getDataGenerator()->create_course($course1);
1781         $course2 = new stdClass();
1782         $course2->fullname = 'Course';
1783         $course2->shortname = 'Two';
1784         $course2 = $this->getDataGenerator()->create_course($course2);
1786         $course3 = new stdClass();
1787         $course3->fullname = 'Course';
1788         $course3->shortname = 'Three search';
1789         $course3 = $this->getDataGenerator()->create_course($course3);
1791         $course4 = new stdClass();
1792         $course4->fullname = 'Course Four';
1793         $course4->shortname = 'CF100';
1794         $course4 = $this->getDataGenerator()->create_course($course4);
1796         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
1797         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'student');
1798         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 'student');
1800         // Add some users as contacts.
1801         message_add_contact($user2->id, 0, $user1->id);
1802         message_add_contact($user3->id, 0, $user1->id);
1803         message_add_contact($user4->id, 0, $user1->id);
1805         // Perform a search.
1806         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
1808         // We need to execute the return values cleaning process to simulate the web service server.
1809         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
1810             $result);
1812         // Confirm that we returns contacts, courses and non-contacts.
1813         $contacts = $result['contacts'];
1814         $courses = $result['courses'];
1815         $noncontacts = $result['noncontacts'];
1817         // Check that we retrieved the correct contacts.
1818         $this->assertCount(2, $contacts);
1819         $this->assertEquals($user3->id, $contacts[0]['userid']);
1820         $this->assertEquals($user2->id, $contacts[1]['userid']);
1822         // Check that we retrieved the correct courses.
1823         $this->assertCount(2, $courses);
1824         $this->assertEquals($course3->id, $courses[0]['id']);
1825         $this->assertEquals($course1->id, $courses[1]['id']);
1827         // Check that we retrieved the correct non-contacts.
1828         $this->assertCount(1, $noncontacts);
1829         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
1830     }
1832     /**
1833      * Tests searching users as another user.
1834      */
1835     public function test_messagearea_search_users_as_other_user() {
1836         $this->resetAfterTest(true);
1838         // The person doing the search.
1839         $this->setAdminUser();
1841         // Create some users.
1842         $user1 = new stdClass();
1843         $user1->firstname = 'User';
1844         $user1->lastname = 'One';
1845         $user1 = self::getDataGenerator()->create_user($user1);
1847         $user2 = new stdClass();
1848         $user2->firstname = 'User search';
1849         $user2->lastname = 'Two';
1850         $user2 = self::getDataGenerator()->create_user($user2);
1852         $user3 = new stdClass();
1853         $user3->firstname = 'User search';
1854         $user3->lastname = 'Three';
1855         $user3 = self::getDataGenerator()->create_user($user3);
1857         $user4 = new stdClass();
1858         $user4->firstname = 'User';
1859         $user4->lastname = 'Four';
1860         $user4 = self::getDataGenerator()->create_user($user4);
1862         $user5 = new stdClass();
1863         $user5->firstname = 'User search';
1864         $user5->lastname = 'Five';
1865         $user5 = self::getDataGenerator()->create_user($user5);
1867         $user6 = new stdClass();
1868         $user6->firstname = 'User';
1869         $user6->lastname = 'Six';
1870         $user6 = self::getDataGenerator()->create_user($user6);
1872         // Create some courses.
1873         $course1 = new stdClass();
1874         $course1->fullname = 'Course search';
1875         $course1->shortname = 'One';
1876         $course1 = $this->getDataGenerator()->create_course($course1);
1878         $course2 = new stdClass();
1879         $course2->fullname = 'Course';
1880         $course2->shortname = 'Two';
1881         $course2 = $this->getDataGenerator()->create_course($course2);
1883         $course3 = new stdClass();
1884         $course3->fullname = 'Course';
1885         $course3->shortname = 'Three search';
1886         $course3 = $this->getDataGenerator()->create_course($course3);
1888         // Add some users as contacts.
1889         message_add_contact($user2->id, 0, $user1->id);
1890         message_add_contact($user3->id, 0, $user1->id);
1891         message_add_contact($user4->id, 0, $user1->id);
1893         // Perform a search.
1894         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
1896         // We need to execute the return values cleaning process to simulate the web service server.
1897         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
1898             $result);
1900         // Confirm that we returns contacts, courses and non-contacts.
1901         $contacts = $result['contacts'];
1902         $courses = $result['courses'];
1903         $noncontacts = $result['noncontacts'];
1905         // Check that we retrieved the correct contacts.
1906         $this->assertCount(2, $contacts);
1907         $this->assertEquals($user3->id, $contacts[0]['userid']);
1908         $this->assertEquals($user2->id, $contacts[1]['userid']);
1910         // Check that we retrieved the correct courses.
1911         $this->assertCount(0, $courses);
1913         // Check that we retrieved the correct non-contacts.
1914         $this->assertCount(1, $noncontacts);
1915         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
1916     }
1918     /**
1919      * Tests searching users as another user without the proper capabilities.
1920      */
1921     public function test_messagearea_search_users_as_other_user_without_cap() {
1922         $this->resetAfterTest(true);
1924         // Create some users.
1925         $user1 = self::getDataGenerator()->create_user();
1926         $user2 = self::getDataGenerator()->create_user();
1928         // The person doing the search for another user.
1929         $this->setUser($user1);
1931         // Ensure an exception is thrown.
1932         $this->expectException('moodle_exception');
1933         core_message_external::data_for_messagearea_search_users($user2->id, 'User');
1934     }
1936     /**
1937      * Tests searching users with messaging disabled.
1938      */
1939     public function test_messagearea_search_users_messaging_disabled() {
1940         global $CFG;
1942         $this->resetAfterTest(true);
1944         // Create some skeleton data just so we can call the WS.
1945         $user = self::getDataGenerator()->create_user();
1947         // The person doing the search.
1948         $this->setUser($user);
1950         // Disable messaging.
1951         $CFG->messaging = 0;
1953         // Ensure an exception is thrown.
1954         $this->expectException('moodle_exception');
1955         core_message_external::data_for_messagearea_search_users($user->id, 'User');
1956     }
1958     /**
1959      * Tests searching messages.
1960      */
1961     public function test_messagearea_search_messages() {
1962         $this->resetAfterTest(true);
1964         // Create some users.
1965         $user1 = self::getDataGenerator()->create_user();
1966         $user2 = self::getDataGenerator()->create_user();
1968         // The person doing the search.
1969         $this->setUser($user1);
1971         // Send some messages back and forth.
1972         $time = time();
1973         $this->send_message($user1, $user2, 'Yo!', 0, $time);
1974         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
1975         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
1976         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
1978         // Perform a search.
1979         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
1981         // We need to execute the return values cleaning process to simulate the web service server.
1982         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
1983             $result);
1985         // Confirm the data is correct.
1986         $messages = $result['contacts'];
1987         $this->assertCount(2, $messages);
1989         $message1 = $messages[0];
1990         $message2 = $messages[1];
1992         $this->assertEquals($user2->id, $message1['userid']);
1993         $this->assertEquals(fullname($user2), $message1['fullname']);
1994         $this->assertTrue($message1['ismessaging']);
1995         $this->assertFalse($message1['sentfromcurrentuser']);
1996         $this->assertEquals('Word.', $message1['lastmessage']);
1997         $this->assertNotEmpty($message1['messageid']);
1998         $this->assertNull($message1['isonline']);
1999         $this->assertFalse($message1['isread']);
2000         $this->assertFalse($message1['isblocked']);
2001         $this->assertNull($message1['unreadcount']);
2003         $this->assertEquals($user2->id, $message2['userid']);
2004         $this->assertEquals(fullname($user2), $message2['fullname']);
2005         $this->assertTrue($message2['ismessaging']);
2006         $this->assertTrue($message2['sentfromcurrentuser']);
2007         $this->assertEquals('Yo!', $message2['lastmessage']);
2008         $this->assertNotEmpty($message2['messageid']);
2009         $this->assertNull($message2['isonline']);
2010         $this->assertTrue($message2['isread']);
2011         $this->assertFalse($message2['isblocked']);
2012         $this->assertNull($message2['unreadcount']);
2013     }
2015     /**
2016      * Tests searching messages as another user.
2017      */
2018     public function test_messagearea_search_messages_as_other_user() {
2019         $this->resetAfterTest(true);
2021         // The person doing the search.
2022         $this->setAdminUser();
2024         // Create some users.
2025         $user1 = self::getDataGenerator()->create_user();
2026         $user2 = self::getDataGenerator()->create_user();
2028         // Send some messages back and forth.
2029         $time = time();
2030         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2031         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2032         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2033         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2035         // Perform a search.
2036         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2038         // We need to execute the return values cleaning process to simulate the web service server.
2039         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2040             $result);
2042         // Confirm the data is correct.
2043         $messages = $result['contacts'];
2044         $this->assertCount(2, $messages);
2046         $message1 = $messages[0];
2047         $message2 = $messages[1];
2049         $this->assertEquals($user2->id, $message1['userid']);
2050         $this->assertEquals(fullname($user2), $message1['fullname']);
2051         $this->assertTrue($message1['ismessaging']);
2052         $this->assertFalse($message1['sentfromcurrentuser']);
2053         $this->assertEquals('Word.', $message1['lastmessage']);
2054         $this->assertNotEmpty($message1['messageid']);
2055         $this->assertFalse($message1['isonline']);
2056         $this->assertFalse($message1['isread']);
2057         $this->assertFalse($message1['isblocked']);
2058         $this->assertNull($message1['unreadcount']);
2060         $this->assertEquals($user2->id, $message2['userid']);
2061         $this->assertEquals(fullname($user2), $message2['fullname']);
2062         $this->assertTrue($message2['ismessaging']);
2063         $this->assertTrue($message2['sentfromcurrentuser']);
2064         $this->assertEquals('Yo!', $message2['lastmessage']);
2065         $this->assertNotEmpty($message2['messageid']);
2066         $this->assertFalse($message2['isonline']);
2067         $this->assertTrue($message2['isread']);
2068         $this->assertFalse($message2['isblocked']);
2069         $this->assertNull($message2['unreadcount']);
2070     }
2072     /**
2073      * Tests searching messages as another user without the proper capabilities.
2074      */
2075     public function test_messagearea_search_messages_as_other_user_without_cap() {
2076         $this->resetAfterTest(true);
2078         // Create some users.
2079         $user1 = self::getDataGenerator()->create_user();
2080         $user2 = self::getDataGenerator()->create_user();
2082         // The person doing the search for another user.
2083         $this->setUser($user1);
2085         // Ensure an exception is thrown.
2086         $this->expectException('moodle_exception');
2087         core_message_external::data_for_messagearea_search_messages($user2->id, 'Search');
2088     }
2090     /**
2091      * Tests searching messages with messaging disabled
2092      */
2093     public function test_messagearea_search_messages_messaging_disabled() {
2094         global $CFG;
2096         $this->resetAfterTest(true);
2098         // Create some skeleton data just so we can call the WS.
2099         $user = self::getDataGenerator()->create_user();
2101         // The person doing the search .
2102         $this->setUser($user);
2104         // Disable messaging.
2105         $CFG->messaging = 0;
2107         // Ensure an exception is thrown.
2108         $this->expectException('moodle_exception');
2109         core_message_external::data_for_messagearea_search_messages($user->id, 'Search');
2110     }
2112     /**
2113      * Tests retrieving conversations.
2114      */
2115     public function test_messagearea_conversations() {
2116         $this->resetAfterTest(true);
2118         // Create some users.
2119         $user1 = self::getDataGenerator()->create_user();
2120         $user2 = self::getDataGenerator()->create_user();
2121         $user3 = self::getDataGenerator()->create_user();
2122         $user4 = self::getDataGenerator()->create_user();
2124         // The person retrieving the conversations.
2125         $this->setUser($user1);
2127         // Send some messages back and forth, have some different conversations with different users.
2128         $time = time();
2129         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2130         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2131         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2132         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2134         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2135         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2136         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2137         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2139         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2140         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2141         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2143         // Retrieve the conversations.
2144         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2146         // We need to execute the return values cleaning process to simulate the web service server.
2147         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2148             $result);
2150         // Confirm the data is correct.
2151         $messages = $result['contacts'];
2152         $this->assertCount(3, $messages);
2154         $message1 = $messages[0];
2155         $message2 = $messages[1];
2156         $message3 = $messages[2];
2158         $this->assertEquals($user4->id, $message1['userid']);
2159         $this->assertTrue($message1['ismessaging']);
2160         $this->assertTrue($message1['sentfromcurrentuser']);
2161         $this->assertEquals('Dope.', $message1['lastmessage']);
2162         $this->assertEquals($messageid3, $message1['messageid']);
2163         $this->assertNull($message1['isonline']);
2164         $this->assertFalse($message1['isread']);
2165         $this->assertFalse($message1['isblocked']);
2166         $this->assertEquals(1, $message1['unreadcount']);
2168         $this->assertEquals($user3->id, $message2['userid']);
2169         $this->assertTrue($message2['ismessaging']);
2170         $this->assertFalse($message2['sentfromcurrentuser']);
2171         $this->assertEquals('Cool.', $message2['lastmessage']);
2172         $this->assertEquals($messageid2, $message2['messageid']);
2173         $this->assertNull($message2['isonline']);
2174         $this->assertFalse($message2['isread']);
2175         $this->assertFalse($message2['isblocked']);
2176         $this->assertEquals(2, $message2['unreadcount']);
2178         $this->assertEquals($user2->id, $message3['userid']);
2179         $this->assertTrue($message3['ismessaging']);
2180         $this->assertFalse($message3['sentfromcurrentuser']);
2181         $this->assertEquals('Word.', $message3['lastmessage']);
2182         $this->assertEquals($messageid1, $message3['messageid']);
2183         $this->assertNull($message3['isonline']);
2184         $this->assertFalse($message3['isread']);
2185         $this->assertFalse($message3['isblocked']);
2186         $this->assertEquals(2, $message3['unreadcount']);
2187     }
2189     /**
2190      * Tests retrieving conversations as another user.
2191      */
2192     public function test_messagearea_conversations_as_other_user() {
2193         $this->resetAfterTest(true);
2195         // Set as admin.
2196         $this->setAdminUser();
2198         // Create some users.
2199         $user1 = self::getDataGenerator()->create_user();
2200         $user2 = self::getDataGenerator()->create_user();
2201         $user3 = self::getDataGenerator()->create_user();
2202         $user4 = self::getDataGenerator()->create_user();
2204         // Send some messages back and forth, have some different conversations with different users.
2205         $time = time();
2206         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2207         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2208         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2209         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2211         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2212         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2213         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2214         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2216         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2217         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2218         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2220         // Retrieve the conversations.
2221         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2223         // We need to execute the return values cleaning process to simulate the web service server.
2224         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2225             $result);
2227         // Confirm the data is correct.
2228         $messages = $result['contacts'];
2229         $this->assertCount(3, $messages);
2231         $message1 = $messages[0];
2232         $message2 = $messages[1];
2233         $message3 = $messages[2];
2235         $this->assertEquals($user4->id, $message1['userid']);
2236         $this->assertTrue($message1['ismessaging']);
2237         $this->assertTrue($message1['sentfromcurrentuser']);
2238         $this->assertEquals('Dope.', $message1['lastmessage']);
2239         $this->assertEquals($messageid3, $message1['messageid']);
2240         $this->assertFalse($message1['isonline']);
2241         $this->assertFalse($message1['isread']);
2242         $this->assertFalse($message1['isblocked']);
2243         $this->assertEquals(1, $message1['unreadcount']);
2245         $this->assertEquals($user3->id, $message2['userid']);
2246         $this->assertTrue($message2['ismessaging']);
2247         $this->assertFalse($message2['sentfromcurrentuser']);
2248         $this->assertEquals('Cool.', $message2['lastmessage']);
2249         $this->assertEquals($messageid2, $message2['messageid']);
2250         $this->assertFalse($message2['isonline']);
2251         $this->assertFalse($message2['isread']);
2252         $this->assertFalse($message2['isblocked']);
2253         $this->assertEquals(2, $message2['unreadcount']);
2255         $this->assertEquals($user2->id, $message3['userid']);
2256         $this->assertTrue($message3['ismessaging']);
2257         $this->assertFalse($message3['sentfromcurrentuser']);
2258         $this->assertEquals('Word.', $message3['lastmessage']);
2259         $this->assertEquals($messageid1, $message3['messageid']);
2260         $this->assertFalse($message3['isonline']);
2261         $this->assertFalse($message3['isread']);
2262         $this->assertFalse($message3['isblocked']);
2263         $this->assertEquals(2, $message3['unreadcount']);
2264     }
2266     /**
2267      * Tests retrieving conversations as another user without the proper capabilities.
2268      */
2269     public function test_messagearea_conversations_as_other_user_without_cap() {
2270         $this->resetAfterTest(true);
2272         // Create some users.
2273         $user1 = self::getDataGenerator()->create_user();
2274         $user2 = self::getDataGenerator()->create_user();
2276         // The person retrieving the conversations for another user.
2277         $this->setUser($user1);
2279         // Ensure an exception is thrown.
2280         $this->expectException('moodle_exception');
2281         core_message_external::data_for_messagearea_conversations($user2->id);
2282     }
2284     /**
2285      * Tests retrieving conversations with messaging disabled.
2286      */
2287     public function test_messagearea_conversations_messaging_disabled() {
2288         global $CFG;
2290         $this->resetAfterTest(true);
2292         // Create some skeleton data just so we can call the WS.
2293         $user = self::getDataGenerator()->create_user();
2295         // The person retrieving the conversations.
2296         $this->setUser($user);
2298         // Disable messaging.
2299         $CFG->messaging = 0;
2301         // Ensure an exception is thrown.
2302         $this->expectException('moodle_exception');
2303         core_message_external::data_for_messagearea_conversations($user->id);
2304     }
2306     /**
2307      * Tests retrieving contacts.
2308      */
2309     public function test_messagearea_contacts() {
2310         $this->resetAfterTest(true);
2312         // Create some users.
2313         $user1 = self::getDataGenerator()->create_user();
2315         // Set as the user.
2316         $this->setUser($user1);
2318         $user2 = new stdClass();
2319         $user2->firstname = 'User';
2320         $user2->lastname = 'A';
2321         $user2 = self::getDataGenerator()->create_user($user2);
2323         $user3 = new stdClass();
2324         $user3->firstname = 'User';
2325         $user3->lastname = 'B';
2326         $user3 = self::getDataGenerator()->create_user($user3);
2328         $user4 = new stdClass();
2329         $user4->firstname = 'User';
2330         $user4->lastname = 'C';
2331         $user4 = self::getDataGenerator()->create_user($user4);
2333         $user5 = new stdClass();
2334         $user5->firstname = 'User';
2335         $user5->lastname = 'D';
2336         $user5 = self::getDataGenerator()->create_user($user5);
2338         // Add some users as contacts.
2339         message_add_contact($user2->id, 0, $user1->id);
2340         message_add_contact($user3->id, 0, $user1->id);
2341         message_add_contact($user4->id, 0, $user1->id);
2343         // Retrieve the contacts.
2344         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2346         // We need to execute the return values cleaning process to simulate the web service server.
2347         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2348             $result);
2350         // Confirm the data is correct.
2351         $contacts = $result['contacts'];
2352         $this->assertCount(3, $contacts);
2354         $contact1 = $contacts[0];
2355         $contact2 = $contacts[1];
2356         $contact3 = $contacts[2];
2358         $this->assertEquals($user2->id, $contact1['userid']);
2359         $this->assertFalse($contact1['ismessaging']);
2360         $this->assertFalse($contact1['sentfromcurrentuser']);
2361         $this->assertNull($contact1['lastmessage']);
2362         $this->assertNull($contact1['messageid']);
2363         $this->assertNull($contact1['isonline']);
2364         $this->assertFalse($contact1['isread']);
2365         $this->assertFalse($contact1['isblocked']);
2366         $this->assertNull($contact1['unreadcount']);
2368         $this->assertEquals($user3->id, $contact2['userid']);
2369         $this->assertFalse($contact2['ismessaging']);
2370         $this->assertFalse($contact2['sentfromcurrentuser']);
2371         $this->assertNull($contact2['lastmessage']);
2372         $this->assertNull($contact2['messageid']);
2373         $this->assertNull($contact2['isonline']);
2374         $this->assertFalse($contact2['isread']);
2375         $this->assertFalse($contact2['isblocked']);
2376         $this->assertNull($contact2['unreadcount']);
2378         $this->assertEquals($user4->id, $contact3['userid']);
2379         $this->assertFalse($contact3['ismessaging']);
2380         $this->assertFalse($contact3['sentfromcurrentuser']);
2381         $this->assertNull($contact3['lastmessage']);
2382         $this->assertNull($contact3['messageid']);
2383         $this->assertNull($contact3['isonline']);
2384         $this->assertFalse($contact3['isread']);
2385         $this->assertFalse($contact3['isblocked']);
2386         $this->assertNull($contact3['unreadcount']);
2387     }
2389     /**
2390      * Tests retrieving contacts as another user.
2391      */
2392     public function test_messagearea_contacts_as_other_user() {
2393         $this->resetAfterTest(true);
2395         $this->setAdminUser();
2397         // Create some users.
2398         $user1 = self::getDataGenerator()->create_user();
2400         $user2 = new stdClass();
2401         $user2->firstname = 'User';
2402         $user2->lastname = 'A';
2403         $user2 = self::getDataGenerator()->create_user($user2);
2405         $user3 = new stdClass();
2406         $user3->firstname = 'User';
2407         $user3->lastname = 'B';
2408         $user3 = self::getDataGenerator()->create_user($user3);
2410         $user4 = new stdClass();
2411         $user4->firstname = 'User';
2412         $user4->lastname = 'C';
2413         $user4 = self::getDataGenerator()->create_user($user4);
2415         $user5 = new stdClass();
2416         $user5->firstname = 'User';
2417         $user5->lastname = 'D';
2418         $user5 = self::getDataGenerator()->create_user($user5);
2420         // Add some users as contacts.
2421         message_add_contact($user2->id, 0, $user1->id);
2422         message_add_contact($user3->id, 0, $user1->id);
2423         message_add_contact($user4->id, 0, $user1->id);
2425         // Retrieve the contacts.
2426         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2428         // We need to execute the return values cleaning process to simulate the web service server.
2429         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2430             $result);
2432         // Confirm the data is correct.
2433         $contacts = $result['contacts'];
2434         $this->assertCount(3, $contacts);
2436         $contact1 = $contacts[0];
2437         $contact2 = $contacts[1];
2438         $contact3 = $contacts[2];
2440         $this->assertEquals($user2->id, $contact1['userid']);
2441         $this->assertFalse($contact1['ismessaging']);
2442         $this->assertFalse($contact1['sentfromcurrentuser']);
2443         $this->assertNull($contact1['lastmessage']);
2444         $this->assertNull($contact1['messageid']);
2445         $this->assertFalse($contact1['isonline']);
2446         $this->assertFalse($contact1['isread']);
2447         $this->assertFalse($contact1['isblocked']);
2448         $this->assertNull($contact1['unreadcount']);
2450         $this->assertEquals($user3->id, $contact2['userid']);
2451         $this->assertFalse($contact2['ismessaging']);
2452         $this->assertFalse($contact2['sentfromcurrentuser']);
2453         $this->assertNull($contact2['lastmessage']);
2454         $this->assertNull($contact2['messageid']);
2455         $this->assertFalse($contact2['isonline']);
2456         $this->assertFalse($contact2['isread']);
2457         $this->assertFalse($contact2['isblocked']);
2458         $this->assertNull($contact2['unreadcount']);
2460         $this->assertEquals($user4->id, $contact3['userid']);
2461         $this->assertFalse($contact3['ismessaging']);
2462         $this->assertFalse($contact3['sentfromcurrentuser']);
2463         $this->assertNull($contact3['lastmessage']);
2464         $this->assertNull($contact3['messageid']);
2465         $this->assertFalse($contact3['isonline']);
2466         $this->assertFalse($contact3['isread']);
2467         $this->assertFalse($contact3['isblocked']);
2468         $this->assertNull($contact3['unreadcount']);
2469     }
2471     /**
2472      * Tests retrieving contacts as another user without the proper capabilities.
2473      */
2474     public function test_messagearea_contacts_as_other_user_without_cap() {
2475         $this->resetAfterTest(true);
2477         // Create some users.
2478         $user1 = self::getDataGenerator()->create_user();
2479         $user2 = self::getDataGenerator()->create_user();
2481         // The person retrieving the contacts for another user.
2482         $this->setUser($user1);
2484         // Perform the WS call and ensure an exception is thrown.
2485         $this->expectException('moodle_exception');
2486         core_message_external::data_for_messagearea_contacts($user2->id);
2487     }
2489     /**
2490      * Tests retrieving contacts with messaging disabled.
2491      */
2492     public function test_messagearea_contacts_messaging_disabled() {
2493         global $CFG;
2495         $this->resetAfterTest(true);
2497         // Create some skeleton data just so we can call the WS.
2498         $user = self::getDataGenerator()->create_user();
2500         // The person retrieving the contacts.
2501         $this->setUser($user);
2503         // Disable messaging.
2504         $CFG->messaging = 0;
2506         // Perform the WS call and ensure we are shown that it is disabled.
2507         $this->expectException('moodle_exception');
2508         core_message_external::data_for_messagearea_contacts($user->id);
2509     }
2511     /**
2512      * Tests retrieving messages.
2513      */
2514     public function test_messagearea_messages() {
2515         $this->resetAfterTest(true);
2517         // Create some users.
2518         $user1 = self::getDataGenerator()->create_user();
2519         $user2 = self::getDataGenerator()->create_user();
2521         // The person asking for the messages.
2522         $this->setUser($user1);
2524         // Send some messages back and forth.
2525         $time = time();
2526         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2527         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2528         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2529         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2531         // Retrieve the messages.
2532         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2534         // We need to execute the return values cleaning process to simulate the web service server.
2535         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2536             $result);
2538         // Check the results are correct.
2539         $this->assertTrue($result['iscurrentuser']);
2540         $this->assertEquals($user1->id, $result['currentuserid']);
2541         $this->assertEquals($user2->id, $result['otheruserid']);
2542         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2543         $this->assertNull($result['isonline']);
2545         // Confirm the message data is correct.
2546         $messages = $result['messages'];
2547         $this->assertCount(4, $messages);
2549         $message1 = $messages[0];
2550         $message2 = $messages[1];
2551         $message3 = $messages[2];
2552         $message4 = $messages[3];
2554         $this->assertEquals($user1->id, $message1['useridfrom']);
2555         $this->assertEquals($user2->id, $message1['useridto']);
2556         $this->assertTrue($message1['displayblocktime']);
2557         $this->assertContains('Yo!', $message1['text']);
2559         $this->assertEquals($user2->id, $message2['useridfrom']);
2560         $this->assertEquals($user1->id, $message2['useridto']);
2561         $this->assertFalse($message2['displayblocktime']);
2562         $this->assertContains('Sup mang?', $message2['text']);
2564         $this->assertEquals($user1->id, $message3['useridfrom']);
2565         $this->assertEquals($user2->id, $message3['useridto']);
2566         $this->assertFalse($message3['displayblocktime']);
2567         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2569         $this->assertEquals($user2->id, $message4['useridfrom']);
2570         $this->assertEquals($user1->id, $message4['useridto']);
2571         $this->assertFalse($message4['displayblocktime']);
2572         $this->assertContains('Word.', $message4['text']);
2573     }
2575     /**
2576      * Tests retrieving messages.
2577      */
2578     public function test_messagearea_messages_timefrom() {
2579         $this->resetAfterTest(true);
2581         // Create some users.
2582         $user1 = self::getDataGenerator()->create_user();
2583         $user2 = self::getDataGenerator()->create_user();
2585         // The person asking for the messages.
2586         $this->setUser($user1);
2588         // Send some messages back and forth.
2589         $time = time();
2590         $this->send_message($user1, $user2, 'Message 1', 0, $time - 4);
2591         $this->send_message($user2, $user1, 'Message 2', 0, $time - 3);
2592         $this->send_message($user1, $user2, 'Message 3', 0, $time - 2);
2593         $this->send_message($user2, $user1, 'Message 4', 0, $time - 1);
2595         // Retrieve the messages from $time - 3, which should be the 3 most recent messages.
2596         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id, 0, 0, false, $time - 3);
2598         // We need to execute the return values cleaning process to simulate the web service server.
2599         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2600             $result);
2602         // Confirm the message data is correct. We shouldn't get 'Message 1' back.
2603         $messages = $result['messages'];
2604         $this->assertCount(3, $messages);
2606         $message1 = $messages[0];
2607         $message2 = $messages[1];
2608         $message3 = $messages[2];
2610         $this->assertContains('Message 2', $message1['text']);
2611         $this->assertContains('Message 3', $message2['text']);
2612         $this->assertContains('Message 4', $message3['text']);
2613     }
2615     /**
2616      * Tests retrieving messages as another user.
2617      */
2618     public function test_messagearea_messages_as_other_user() {
2619         $this->resetAfterTest(true);
2621         // Set as admin.
2622         $this->setAdminUser();
2624         // Create some users.
2625         $user1 = self::getDataGenerator()->create_user();
2626         $user2 = self::getDataGenerator()->create_user();
2628         // Send some messages back and forth.
2629         $time = time();
2630         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2631         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2632         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2633         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2635         // Retrieve the messages.
2636         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2638         // We need to execute the return values cleaning process to simulate the web service server.
2639         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2640             $result);
2642         // Check the results are correct.
2643         $this->assertFalse($result['iscurrentuser']);
2644         $this->assertEquals($user1->id, $result['currentuserid']);
2645         $this->assertEquals($user2->id, $result['otheruserid']);
2646         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2647         $this->assertFalse($result['isonline']);
2649         // Confirm the message data is correct.
2650         $messages = $result['messages'];
2651         $this->assertCount(4, $messages);
2653         $message1 = $messages[0];
2654         $message2 = $messages[1];
2655         $message3 = $messages[2];
2656         $message4 = $messages[3];
2658         $this->assertEquals($user1->id, $message1['useridfrom']);
2659         $this->assertEquals($user2->id, $message1['useridto']);
2660         $this->assertTrue($message1['displayblocktime']);
2661         $this->assertContains('Yo!', $message1['text']);
2663         $this->assertEquals($user2->id, $message2['useridfrom']);
2664         $this->assertEquals($user1->id, $message2['useridto']);
2665         $this->assertFalse($message2['displayblocktime']);
2666         $this->assertContains('Sup mang?', $message2['text']);
2668         $this->assertEquals($user1->id, $message3['useridfrom']);
2669         $this->assertEquals($user2->id, $message3['useridto']);
2670         $this->assertFalse($message3['displayblocktime']);
2671         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2673         $this->assertEquals($user2->id, $message4['useridfrom']);
2674         $this->assertEquals($user1->id, $message4['useridto']);
2675         $this->assertFalse($message4['displayblocktime']);
2676         $this->assertContains('Word.', $message4['text']);
2677     }
2679     /**
2680      * Tests retrieving messages as another user without the proper capabilities.
2681      */
2682     public function test_messagearea_messages_as_other_user_without_cap() {
2683         $this->resetAfterTest(true);
2685         // Create some users.
2686         $user1 = self::getDataGenerator()->create_user();
2687         $user2 = self::getDataGenerator()->create_user();
2688         $user3 = self::getDataGenerator()->create_user();
2690         // The person asking for the messages for another user.
2691         $this->setUser($user1);
2693         // Ensure an exception is thrown.
2694         $this->expectException('moodle_exception');
2695         core_message_external::data_for_messagearea_messages($user2->id, $user3->id);
2696     }
2698     /**
2699      * Tests retrieving messages with messaging disabled.
2700      */
2701     public function test_messagearea_messages_messaging_disabled() {
2702         global $CFG;
2704         $this->resetAfterTest(true);
2706         // Create some skeleton data just so we can call the WS.
2707         $user1 = self::getDataGenerator()->create_user();
2708         $user2 = self::getDataGenerator()->create_user();
2710         // The person asking for the messages for another user.
2711         $this->setUser($user1);
2713         // Disable messaging.
2714         $CFG->messaging = 0;
2716         // Ensure an exception is thrown.
2717         $this->expectException('moodle_exception');
2718         core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2719     }
2721     /**
2722      * Tests retrieving most recent message.
2723      */
2724     public function test_messagearea_get_most_recent_message() {
2725         $this->resetAfterTest(true);
2727         // Create some users.
2728         $user1 = self::getDataGenerator()->create_user();
2729         $user2 = self::getDataGenerator()->create_user();
2731         // The person doing the search.
2732         $this->setUser($user1);
2734         // Send some messages back and forth.
2735         $time = time();
2736         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2737         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2738         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2739         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2741         // Get the most recent message.
2742         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
2744         // We need to execute the return values cleaning process to simulate the web service server.
2745         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
2746             $result);
2748         // Check the results are correct.
2749         $this->assertEquals($user2->id, $result['useridfrom']);
2750         $this->assertEquals($user1->id, $result['useridto']);
2751         $this->assertContains('Word.', $result['text']);
2752     }
2754     /**
2755      * Tests retrieving most recent message as another user.
2756      */
2757     public function test_messagearea_get_most_recent_message_as_other_user() {
2758         $this->resetAfterTest(true);
2760         // The person doing the search.
2761         $this->setAdminUser();
2763         // Create some users.
2764         $user1 = self::getDataGenerator()->create_user();
2765         $user2 = self::getDataGenerator()->create_user();
2767         // Send some messages back and forth.
2768         $time = time();
2769         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2770         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2771         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2772         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2774         // Get the most recent message.
2775         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
2777         // We need to execute the return values cleaning process to simulate the web service server.
2778         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
2779             $result);
2781         // Check the results are correct.
2782         $this->assertEquals($user2->id, $result['useridfrom']);
2783         $this->assertEquals($user1->id, $result['useridto']);
2784         $this->assertContains('Word.', $result['text']);
2785     }
2787     /**
2788      * Tests retrieving most recent message as another user without the proper capabilities.
2789      */
2790     public function test_messagearea_get_most_recent_message_as_other_user_without_cap() {
2791         $this->resetAfterTest(true);
2793         // Create some users.
2794         $user1 = self::getDataGenerator()->create_user();
2795         $user2 = self::getDataGenerator()->create_user();
2796         $user3 = self::getDataGenerator()->create_user();
2798         // The person asking for the most recent message for another user.
2799         $this->setUser($user1);
2801         // Ensure an exception is thrown.
2802         $this->expectException('moodle_exception');
2803         core_message_external::data_for_messagearea_get_most_recent_message($user2->id, $user3->id);
2804     }
2806     /**
2807      * Tests retrieving most recent message with messaging disabled.
2808      */
2809     public function test_messagearea_get_most_recent_message_messaging_disabled() {
2810         global $CFG;
2812         $this->resetAfterTest(true);
2814         // Create some skeleton data just so we can call the WS.
2815         $user1 = self::getDataGenerator()->create_user();
2816         $user2 = self::getDataGenerator()->create_user();
2818         // The person asking for the most recent message.
2819         $this->setUser($user1);
2821         // Disable messaging.
2822         $CFG->messaging = 0;
2824         // Ensure an exception is thrown.
2825         $this->expectException('moodle_exception');
2826         core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
2827     }
2829     /**
2830      * Tests retrieving a user's profile.
2831      */
2832     public function test_messagearea_get_profile() {
2833         $this->resetAfterTest(true);
2835         // Create some users.
2836         $user1 = self::getDataGenerator()->create_user();
2837         $user2 = self::getDataGenerator()->create_user();
2839         // The person asking for the profile information.
2840         $this->setUser($user1);
2842         // Get the profile.
2843         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
2845         // We need to execute the return values cleaning process to simulate the web service server.
2846         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_profile_returns(),
2847             $result);
2849         $this->assertEquals($user2->id, $result['userid']);
2850         $this->assertEmpty($result['email']);
2851         $this->assertEmpty($result['country']);
2852         $this->assertEmpty($result['city']);
2853         $this->assertEquals(fullname($user2), $result['fullname']);
2854         $this->assertNull($result['isonline']);
2855         $this->assertFalse($result['isblocked']);
2856         $this->assertFalse($result['iscontact']);
2857     }
2859     /**
2860      * Tests retrieving a user's profile as another user.
2861      */
2862     public function test_messagearea_profile_as_other_user() {
2863         $this->resetAfterTest(true);
2865         // The person asking for the profile information.
2866         $this->setAdminUser();
2868         // Create some users.
2869         $user1 = self::getDataGenerator()->create_user();
2871         $user2 = new stdClass();
2872         $user2->country = 'AU';
2873         $user2->city = 'Perth';
2874         $user2 = self::getDataGenerator()->create_user($user2);
2876         // Get the profile.
2877         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
2879         // We need to execute the return values cleaning process to simulate the web service server.
2880         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_profile_returns(),
2881             $result);
2883         $this->assertEquals($user2->id, $result['userid']);
2884         $this->assertEquals($user2->email, $result['email']);
2885         $this->assertEquals(get_string($user2->country, 'countries'), $result['country']);
2886         $this->assertEquals($user2->city, $result['city']);
2887         $this->assertEquals(fullname($user2), $result['fullname']);
2888         $this->assertFalse($result['isonline']);
2889         $this->assertFalse($result['isblocked']);
2890         $this->assertFalse($result['iscontact']);
2891     }
2893     /**
2894      * Tests retrieving a user's profile as another user without the proper capabilities.
2895      */
2896     public function test_messagearea_profile_as_other_user_without_cap() {
2897         $this->resetAfterTest(true);
2899         // Create some users.
2900         $user1 = self::getDataGenerator()->create_user();
2901         $user2 = self::getDataGenerator()->create_user();
2902         $user3 = self::getDataGenerator()->create_user();
2904         // The person asking for the profile information for another user.
2905         $this->setUser($user1);
2907         // Ensure an exception is thrown.
2908         $this->expectException('moodle_exception');
2909         core_message_external::data_for_messagearea_get_profile($user2->id, $user3->id);
2910     }
2912     /**
2913      * Tests retrieving a user's profile with messaging disabled.
2914      */
2915     public function test_messagearea_profile_messaging_disabled() {
2916         global $CFG;
2918         $this->resetAfterTest(true);
2920         // Create some skeleton data just so we can call the WS.
2921         $user1 = self::getDataGenerator()->create_user();
2922         $user2 = self::getDataGenerator()->create_user();
2924         // The person asking for the profile information.
2925         $this->setUser($user1);
2927         // Disable messaging.
2928         $CFG->messaging = 0;
2930         // Ensure an exception is thrown.
2931         $this->expectException('moodle_exception');
2932         core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
2933     }
2935     /**
2936      * Test marking all message as read with an invalid user.
2937      */
2938     public function test_mark_all_messages_as_read_invalid_user_exception() {
2939         $this->resetAfterTest(true);
2941         $this->expectException('moodle_exception');
2942         core_message_external::mark_all_messages_as_read(-2132131, 0);
2943     }
2945     /**
2946      * Test marking all message as read without proper access.
2947      */
2948     public function test_mark_all_messages_as_read_access_denied_exception() {
2949         $this->resetAfterTest(true);
2951         $sender = $this->getDataGenerator()->create_user();
2952         $user = $this->getDataGenerator()->create_user();
2954         $this->setUser($user);
2955         $this->expectException('moodle_exception');
2956         core_message_external::mark_all_messages_as_read($sender->id, 0);
2957     }
2959     /**
2960      * Test marking all message as read with missing from user.
2961      */
2962     public function test_mark_all_messages_as_read_missing_from_user_exception() {
2963         $this->resetAfterTest(true);
2965         $sender = $this->getDataGenerator()->create_user();
2967         $this->setUser($sender);
2968         $this->expectException('moodle_exception');
2969         core_message_external::mark_all_messages_as_read($sender->id, 99999);
2970     }
2972     /**
2973      * Test marking all message as read.
2974      */
2975     public function test_mark_all_messages_as_read() {
2976         global $DB;
2978         $this->resetAfterTest(true);
2980         $sender1 = $this->getDataGenerator()->create_user();
2981         $sender2 = $this->getDataGenerator()->create_user();
2982         $sender3 = $this->getDataGenerator()->create_user();
2983         $recipient = $this->getDataGenerator()->create_user();
2985         $this->setUser($recipient);
2987         $this->send_message($sender1, $recipient, 'Message');
2988         $this->send_message($sender1, $recipient, 'Message');
2989         $this->send_message($sender2, $recipient, 'Message');
2990         $this->send_message($sender2, $recipient, 'Message');
2991         $this->send_message($sender3, $recipient, 'Message');
2992         $this->send_message($sender3, $recipient, 'Message');
2994         core_message_external::mark_all_messages_as_read($recipient->id, $sender1->id);
2995         $this->assertEquals(2, $DB->count_records('message_user_actions'));
2997         core_message_external::mark_all_messages_as_read($recipient->id, 0);
2998         $this->assertEquals(6, $DB->count_records('message_user_actions'));
2999     }
3001     /**
3002      * Test getting unread conversation count.
3003      */
3004     public function test_get_unread_conversations_count() {
3005         $this->resetAfterTest(true);
3007         // Create some users.
3008         $user1 = self::getDataGenerator()->create_user();
3009         $user2 = self::getDataGenerator()->create_user();
3010         $user3 = self::getDataGenerator()->create_user();
3011         $user4 = self::getDataGenerator()->create_user();
3013         // The person wanting the conversation count.
3014         $this->setUser($user1);
3016         // Send some messages back and forth, have some different conversations with different users.
3017         $this->send_message($user1, $user2, 'Yo!');
3018         $this->send_message($user2, $user1, 'Sup mang?');
3019         $this->send_message($user1, $user2, 'Writing PHPUnit tests!');
3020         $this->send_message($user2, $user1, 'Word.');
3022         $this->send_message($user1, $user3, 'Booyah');
3023         $this->send_message($user3, $user1, 'Whaaat?');
3024         $this->send_message($user1, $user3, 'Nothing.');
3025         $this->send_message($user3, $user1, 'Cool.');
3027         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
3028         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
3029         $this->send_message($user1, $user4, 'Dope.');
3031         // Get the unread conversation count.
3032         $result = core_message_external::get_unread_conversations_count($user1->id);
3034         // We need to execute the return values cleaning process to simulate the web service server.
3035         $result = external_api::clean_returnvalue(core_message_external::get_unread_conversations_count_returns(),
3036             $result);
3038         $this->assertEquals(3, $result);
3039     }
3041     /**
3042      * Test getting unread conversation count as other user.
3043      */
3044     public function test_get_unread_conversations_count_as_other_user() {
3045         $this->resetAfterTest(true);
3047         // The person wanting the conversation count.
3048         $this->setAdminUser();
3050         // Create some users.
3051         $user1 = self::getDataGenerator()->create_user();
3052         $user2 = self::getDataGenerator()->create_user();
3053         $user3 = self::getDataGenerator()->create_user();
3054         $user4 = self::getDataGenerator()->create_user();
3056         // Send some messages back and forth, have some different conversations with different users.
3057         $this->send_message($user1, $user2, 'Yo!');
3058         $this->send_message($user2, $user1, 'Sup mang?');
3059         $this->send_message($user1, $user2, 'Writing PHPUnit tests!');
3060         $this->send_message($user2, $user1, 'Word.');
3062         $this->send_message($user1, $user3, 'Booyah');
3063         $this->send_message($user3, $user1, 'Whaaat?');
3064         $this->send_message($user1, $user3, 'Nothing.');
3065         $this->send_message($user3, $user1, 'Cool.');
3067         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
3068         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
3069         $this->send_message($user1, $user4, 'Dope.');
3071         // Get the unread conversation count.
3072         $result = core_message_external::get_unread_conversations_count($user1->id);
3074         // We need to execute the return values cleaning process to simulate the web service server.
3075         $result = external_api::clean_returnvalue(core_message_external::get_unread_conversations_count_returns(),
3076             $result);
3078         $this->assertEquals(3, $result);
3079     }
3081     /**
3082      * Test getting unread conversation count as other user without proper capability.
3083      */
3084     public function test_get_unread_conversations_count_as_other_user_without_cap() {
3085         $this->resetAfterTest(true);
3087         // Create some users.
3088         $user1 = self::getDataGenerator()->create_user();
3089         $user2 = self::getDataGenerator()->create_user();
3091         // The person wanting the conversation count.
3092         $this->setUser($user1);
3094         // Ensure an exception is thrown.
3095         $this->expectException('moodle_exception');
3096         core_message_external::get_unread_conversations_count($user2->id);
3097     }
3099     /**
3100      * Test deleting conversation.
3101      */
3102     public function test_delete_conversation() {
3103         global $DB;
3105         $this->resetAfterTest(true);
3107         // Create some users.
3108         $user1 = self::getDataGenerator()->create_user();
3109         $user2 = self::getDataGenerator()->create_user();
3111         // The person wanting to delete the conversation.
3112         $this->setUser($user1);
3114         // Send some messages back and forth.
3115         $time = time();
3116         $m1id = $this->send_message($user1, $user2, 'Yo!', 0, $time);
3117         $m2id = $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3118         $m3id = $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3119         $m4id = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3121         // Delete the conversation.
3122         core_message_external::delete_conversation($user1->id, $user2->id);
3124         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
3125         $this->assertCount(4, $muas);
3126         // Sort by id.
3127         ksort($muas);
3129         $mua1 = array_shift($muas);
3130         $mua2 = array_shift($muas);
3131         $mua3 = array_shift($muas);
3132         $mua4 = array_shift($muas);
3134         $this->assertEquals($user1->id, $mua1->userid);
3135         $this->assertEquals($m1id, $mua1->messageid);
3136         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
3138         $this->assertEquals($user1->id, $mua2->userid);
3139         $this->assertEquals($m2id, $mua2->messageid);
3140         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
3142         $this->assertEquals($user1->id, $mua3->userid);
3143         $this->assertEquals($m3id, $mua3->messageid);
3144         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
3146         $this->assertEquals($user1->id, $mua4->userid);
3147         $this->assertEquals($m4id, $mua4->messageid);
3148         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
3149     }
3151     /**
3152      * Test deleting conversation as other user.
3153      */
3154     public function test_delete_conversation_as_other_user() {
3155         global $DB;
3157         $this->resetAfterTest(true);
3159         $this->setAdminUser();
3161         // Create some users.
3162         $user1 = self::getDataGenerator()->create_user();
3163         $user2 = self::getDataGenerator()->create_user();
3165         // Send some messages back and forth.
3166         $time = time();
3167         $m1id = $this->send_message($user1, $user2, 'Yo!', 0, $time);
3168         $m2id = $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3169         $m3id = $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3170         $m4id = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3172         // Delete the conversation.
3173         core_message_external::delete_conversation($user1->id, $user2->id);
3175         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
3176         $this->assertCount(4, $muas);
3177         // Sort by id.
3178         ksort($muas);
3180         $mua1 = array_shift($muas);
3181         $mua2 = array_shift($muas);
3182         $mua3 = array_shift($muas);
3183         $mua4 = array_shift($muas);
3185         $this->assertEquals($user1->id, $mua1->userid);
3186         $this->assertEquals($m1id, $mua1->messageid);
3187         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
3189         $this->assertEquals($user1->id, $mua2->userid);
3190         $this->assertEquals($m2id, $mua2->messageid);
3191         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
3193         $this->assertEquals($user1->id, $mua3->userid);
3194         $this->assertEquals($m3id, $mua3->messageid);
3195         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
3197         $this->assertEquals($user1->id, $mua4->userid);
3198         $this->assertEquals($m4id, $mua4->messageid);
3199         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
3200     }
3202     /**
3203      * Test deleting conversation as other user without proper capability.
3204      */
3205     public function test_delete_conversation_as_other_user_without_cap() {
3206         $this->resetAfterTest(true);
3208         // Create some users.
3209         $user1 = self::getDataGenerator()->create_user();
3210         $user2 = self::getDataGenerator()->create_user();
3211         $user3 = self::getDataGenerator()->create_user();
3213         // The person wanting to delete the conversation.
3214         $this->setUser($user3);
3216         // Ensure an exception is thrown.
3217         $this->expectException('moodle_exception');
3218         core_message_external::delete_conversation($user1->id, $user2->id);
3219     }
3221     /**
3222      * Test deleting conversation with messaging disabled.
3223      */
3224     public function test_delete_conversation_messaging_disabled() {
3225         global $CFG;
3227         $this->resetAfterTest(true);
3229         // Create some users.
3230         $user1 = self::getDataGenerator()->create_user();
3231         $user2 = self::getDataGenerator()->create_user();
3233         // The person wanting to delete the conversation.
3234         $this->setUser($user1);
3236         // Disable messaging.
3237         $CFG->messaging = 0;
3239         // Ensure an exception is thrown.
3240         $this->expectException('moodle_exception');
3241         core_message_external::delete_conversation($user1->id, $user2->id);
3242     }
3244     /**
3245      * Test get message processor.
3246      */
3247     public function test_get_message_processor() {
3248         $this->resetAfterTest(true);
3250         // Create a user.
3251         $user1 = self::getDataGenerator()->create_user();
3253         // Set you as the user.
3254         $this->setUser($user1);
3256         // Get the message processors.
3257         $result = core_message_external::get_message_processor($user1->id, 'popup');
3259         // We need to execute the return values cleaning process to simulate the web service server.
3260         $result = external_api::clean_returnvalue(core_message_external::get_message_processor_returns(), $result);
3262         $this->assertNotEmpty($result['systemconfigured']);
3263         $this->assertNotEmpty($result['userconfigured']);
3264     }
3266     /**
3267      * Test get_user_notification_preferences
3268      */
3269     public function test_get_user_message_preferences() {
3270         $this->resetAfterTest(true);
3272         $user = self::getDataGenerator()->create_user();
3273         $this->setUser($user);
3275         // Set a couple of preferences to test.
3276         set_user_preference('message_provider_moodle_instantmessage_loggedin', 'email', $user);
3277         set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'email', $user);
3278         set_user_preference('message_blocknoncontacts', 1, $user);
3280         $prefs = core_message_external::get_user_message_preferences();
3281         $prefs = external_api::clean_returnvalue(core_message_external::get_user_message_preferences_returns(), $prefs);
3282         $this->assertEquals($user->id, $prefs['preferences']['userid']);
3284         // Check components.
3285         $this->assertCount(1, $prefs['preferences']['components']);
3286         $this->assertTrue($prefs['blocknoncontacts']);
3288         // Check some preferences that we previously set.
3289         $found = false;
3290         foreach ($prefs['preferences']['components'] as $component) {
3291             foreach ($component['notifications'] as $prefdata) {
3292                 if ($prefdata['preferencekey'] != 'message_provider_moodle_instantmessage') {
3293                     continue;
3294                 }
3295                 foreach ($prefdata['processors'] as $processor) {
3296                     if ($processor['name'] == 'email') {
3297                         $this->assertTrue($processor['loggedin']['checked']);
3298                         $this->assertTrue($processor['loggedoff']['checked']);
3299                         $found = true;
3300                     }
3301                 }
3302             }
3303         }
3304         $this->assertTrue($found);
3305     }
3307     /**
3308      * Test get_user_message_preferences permissions
3309      */
3310     public function test_get_user_message_preferences_permissions() {
3311         $this->resetAfterTest(true);
3313         $user = self::getDataGenerator()->create_user();
3314         $otheruser = self::getDataGenerator()->create_user();
3315         $this->setUser($user);
3317         $this->expectException('moodle_exception');
3318         $prefs = core_message_external::get_user_message_preferences($otheruser->id);
3319     }