MDL-52347 behat: fix random failures on fast computer
[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      */
55     protected function send_message($userfrom, $userto, $message = 'Hello world!') {
56         global $DB;
57         $record = new stdClass();
58         $record->useridfrom = $userfrom->id;
59         $record->useridto = $userto->id;
60         $record->subject = 'No subject';
61         $record->fullmessage = $message;
62         $record->timecreated = time();
63         $insert = $DB->insert_record('message', $record);
64     }
66     /**
67      * Test send_instant_messages
68      */
69     public function test_send_instant_messages() {
71         global $DB, $USER, $CFG;
73         $this->resetAfterTest(true);
74         // Transactions used in tests, tell phpunit use alternative reset method.
75         $this->preventResetByRollback();
77         // Turn off all message processors (so nothing is really sent)
78         require_once($CFG->dirroot . '/message/lib.php');
79         $messageprocessors = get_message_processors();
80         foreach($messageprocessors as $messageprocessor) {
81             $messageprocessor->enabled = 0;
82             $DB->update_record('message_processors', $messageprocessor);
83         }
85         // Set the required capabilities by the external function
86         $contextid = context_system::instance()->id;
87         $roleid = $this->assignUserCapability('moodle/site:sendmessage', $contextid);
89         $user1 = self::getDataGenerator()->create_user();
91         // Create test message data.
92         $message1 = array();
93         $message1['touserid'] = $user1->id;
94         $message1['text'] = 'the message.';
95         $message1['clientmsgid'] = 4;
96         $messages = array($message1);
98         $sentmessages = core_message_external::send_instant_messages($messages);
100         // We need to execute the return values cleaning process to simulate the web service server.
101         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
103         $themessage = $DB->get_record('message', array('id' => $sentmessages[0]['msgid']));
105         // Confirm that the message was inserted correctly.
106         $this->assertEquals($themessage->useridfrom, $USER->id);
107         $this->assertEquals($themessage->useridto, $message1['touserid']);
108         $this->assertEquals($themessage->smallmessage, $message1['text']);
109         $this->assertEquals($sentmessages[0]['clientmsgid'], $message1['clientmsgid']);
110     }
112     /**
113      * Test create_contacts.
114      */
115     public function test_create_contacts() {
116         $this->resetAfterTest(true);
118         $user1 = self::getDataGenerator()->create_user();
119         $user2 = self::getDataGenerator()->create_user();
120         $user3 = self::getDataGenerator()->create_user();
121         $user4 = self::getDataGenerator()->create_user();
122         $user5 = self::getDataGenerator()->create_user();
123         $this->setUser($user1);
125         // Adding a contact.
126         $return = core_message_external::create_contacts(array($user2->id));
127         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
128         $this->assertEquals(array(), $return);
130         // Adding a contact who is already a contact.
131         $return = core_message_external::create_contacts(array($user2->id));
132         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
133         $this->assertEquals(array(), $return);
135         // Adding multiple contacts.
136         $return = core_message_external::create_contacts(array($user3->id, $user4->id));
137         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
138         $this->assertEquals(array(), $return);
140         // Adding a non-existing user.
141         $return = core_message_external::create_contacts(array(99999));
142         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
143         $this->assertCount(1, $return);
144         $return = array_pop($return);
145         $this->assertEquals($return['warningcode'], 'contactnotcreated');
146         $this->assertEquals($return['itemid'], 99999);
148         // Adding contacts with valid and invalid parameters.
149         $return = core_message_external::create_contacts(array($user5->id, 99999));
150         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
151         $this->assertCount(1, $return);
152         $return = array_pop($return);
153         $this->assertEquals($return['warningcode'], 'contactnotcreated');
154         $this->assertEquals($return['itemid'], 99999);
155     }
157     /**
158      * Test delete_contacts.
159      */
160     public function test_delete_contacts() {
161         $this->resetAfterTest(true);
163         $user1 = self::getDataGenerator()->create_user();
164         $user2 = self::getDataGenerator()->create_user();
165         $user3 = self::getDataGenerator()->create_user();
166         $user4 = self::getDataGenerator()->create_user();
167         $user5 = self::getDataGenerator()->create_user();
168         $user6 = self::getDataGenerator()->create_user();
169         $this->setUser($user1);
170         $this->assertEquals(array(), core_message_external::create_contacts(
171             array($user3->id, $user4->id, $user5->id, $user6->id)));
173         // Removing a non-contact.
174         $return = core_message_external::delete_contacts(array($user2->id));
175         $this->assertNull($return);
177         // Removing one contact.
178         $return = core_message_external::delete_contacts(array($user3->id));
179         $this->assertNull($return);
181         // Removing multiple contacts.
182         $return = core_message_external::delete_contacts(array($user4->id, $user5->id));
183         $this->assertNull($return);
185         // Removing contact from unexisting user.
186         $return = core_message_external::delete_contacts(array(99999));
187         $this->assertNull($return);
189         // Removing mixed valid and invalid data.
190         $return = core_message_external::delete_contacts(array($user6->id, 99999));
191         $this->assertNull($return);
192     }
194     /**
195      * Test block_contacts.
196      */
197     public function test_block_contacts() {
198         $this->resetAfterTest(true);
200         $user1 = self::getDataGenerator()->create_user();
201         $user2 = self::getDataGenerator()->create_user();
202         $user3 = self::getDataGenerator()->create_user();
203         $user4 = self::getDataGenerator()->create_user();
204         $user5 = self::getDataGenerator()->create_user();
205         $this->setUser($user1);
206         $this->assertEquals(array(), core_message_external::create_contacts(array($user3->id, $user4->id, $user5->id)));
208         // Blocking a contact.
209         $return = core_message_external::block_contacts(array($user2->id));
210         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
211         $this->assertEquals(array(), $return);
213         // Blocking a contact who is already a contact.
214         $return = core_message_external::block_contacts(array($user2->id));
215         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
216         $this->assertEquals(array(), $return);
218         // Blocking multiple contacts.
219         $return = core_message_external::block_contacts(array($user3->id, $user4->id));
220         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
221         $this->assertEquals(array(), $return);
223         // Blocking a non-existing user.
224         $return = core_message_external::block_contacts(array(99999));
225         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
226         $this->assertCount(1, $return);
227         $return = array_pop($return);
228         $this->assertEquals($return['warningcode'], 'contactnotblocked');
229         $this->assertEquals($return['itemid'], 99999);
231         // Blocking contacts with valid and invalid parameters.
232         $return = core_message_external::block_contacts(array($user5->id, 99999));
233         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
234         $this->assertCount(1, $return);
235         $return = array_pop($return);
236         $this->assertEquals($return['warningcode'], 'contactnotblocked');
237         $this->assertEquals($return['itemid'], 99999);
238     }
240     /**
241      * Test unblock_contacts.
242      */
243     public function test_unblock_contacts() {
244         $this->resetAfterTest(true);
246         $user1 = self::getDataGenerator()->create_user();
247         $user2 = self::getDataGenerator()->create_user();
248         $user3 = self::getDataGenerator()->create_user();
249         $user4 = self::getDataGenerator()->create_user();
250         $user5 = self::getDataGenerator()->create_user();
251         $user6 = self::getDataGenerator()->create_user();
252         $this->setUser($user1);
253         $this->assertEquals(array(), core_message_external::create_contacts(
254             array($user3->id, $user4->id, $user5->id, $user6->id)));
256         // Removing a non-contact.
257         $return = core_message_external::unblock_contacts(array($user2->id));
258         $this->assertNull($return);
260         // Removing one contact.
261         $return = core_message_external::unblock_contacts(array($user3->id));
262         $this->assertNull($return);
264         // Removing multiple contacts.
265         $return = core_message_external::unblock_contacts(array($user4->id, $user5->id));
266         $this->assertNull($return);
268         // Removing contact from unexisting user.
269         $return = core_message_external::unblock_contacts(array(99999));
270         $this->assertNull($return);
272         // Removing mixed valid and invalid data.
273         $return = core_message_external::unblock_contacts(array($user6->id, 99999));
274         $this->assertNull($return);
276     }
278     /**
279      * Test get_contacts.
280      */
281     public function test_get_contacts() {
282         $this->resetAfterTest(true);
284         $user1 = self::getDataGenerator()->create_user();
285         $user_stranger = self::getDataGenerator()->create_user();
286         $user_offline1 = self::getDataGenerator()->create_user();
287         $user_offline2 = self::getDataGenerator()->create_user();
288         $user_offline3 = self::getDataGenerator()->create_user();
289         $user_online = new stdClass();
290         $user_online->lastaccess = time();
291         $user_online = self::getDataGenerator()->create_user($user_online);
292         $user_blocked = self::getDataGenerator()->create_user();
293         $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
295         // Login as user1.
296         $this->setUser($user1);
297         $this->assertEquals(array(), core_message_external::create_contacts(
298             array($user_offline1->id, $user_offline2->id, $user_offline3->id, $user_online->id)));
300         // User_stranger sends a couple of messages to user1.
301         $this->send_message($user_stranger, $user1, 'Hello there!');
302         $this->send_message($user_stranger, $user1, 'How you goin?');
303         $this->send_message($user_stranger, $user1, 'Cya!');
304         $this->send_message($noreplyuser, $user1, 'I am not a real user');
306         // User_blocked sends a message to user1.
307         $this->send_message($user_blocked, $user1, 'Here, have some spam.');
309         // Retrieve the contacts of the user.
310         $this->setUser($user1);
311         $contacts = core_message_external::get_contacts();
312         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
313         $this->assertCount(3, $contacts['offline']);
314         $this->assertCount(1, $contacts['online']);
315         $this->assertCount(3, $contacts['strangers']);
316         core_message_external::block_contacts(array($user_blocked->id));
317         $contacts = core_message_external::get_contacts();
318         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
319         $this->assertCount(3, $contacts['offline']);
320         $this->assertCount(1, $contacts['online']);
321         $this->assertCount(2, $contacts['strangers']);
323         // Checking some of the fields returned.
324         $stranger = array_pop($contacts['strangers']);
326         $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
327         $this->assertEquals(1, $stranger['unread']);
329         // Check that deleted users are not returned.
330         delete_user($user_offline1);
331         delete_user($user_stranger);
332         delete_user($user_online);
333         $contacts = core_message_external::get_contacts();
334         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
335         $this->assertCount(2, $contacts['offline']);
336         $this->assertCount(0, $contacts['online']);
337         $this->assertCount(1, $contacts['strangers']);
338     }
340     /**
341      * Test search_contacts.
342      */
343     public function test_search_contacts() {
344         global $DB;
345         $this->resetAfterTest(true);
347         $course1 = $this->getDataGenerator()->create_course();
348         $course2 = $this->getDataGenerator()->create_course();
350         $user1 = new stdClass();
351         $user1->firstname = 'X';
352         $user1->lastname = 'X';
353         $user1 = $this->getDataGenerator()->create_user($user1);
354         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
355         $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
357         $user2 = new stdClass();
358         $user2->firstname = 'Eric';
359         $user2->lastname = 'Cartman';
360         $user2 = self::getDataGenerator()->create_user($user2);
361         $user3 = new stdClass();
362         $user3->firstname = 'Stan';
363         $user3->lastname = 'Marsh';
364         $user3 = self::getDataGenerator()->create_user($user3);
365         self::getDataGenerator()->enrol_user($user3->id, $course1->id);
366         $user4 = new stdClass();
367         $user4->firstname = 'Kyle';
368         $user4->lastname = 'Broflovski';
369         $user4 = self::getDataGenerator()->create_user($user4);
370         $user5 = new stdClass();
371         $user5->firstname = 'Kenny';
372         $user5->lastname = 'McCormick';
373         $user5 = self::getDataGenerator()->create_user($user5);
374         self::getDataGenerator()->enrol_user($user5->id, $course2->id);
376         $this->setUser($user1);
378         $results = core_message_external::search_contacts('r');
379         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
380         $this->assertCount(5, $results); // Users 2 through 5 + admin
382         $results = core_message_external::search_contacts('r', true);
383         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
384         $this->assertCount(2, $results);
386         $results = core_message_external::search_contacts('Kyle', false);
387         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
388         $this->assertCount(1, $results);
389         $result = reset($results);
390         $this->assertEquals($user4->id, $result['id']);
392         $results = core_message_external::search_contacts('y', false);
393         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
394         $this->assertCount(2, $results);
396         $results = core_message_external::search_contacts('y', true);
397         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
398         $this->assertCount(1, $results);
399         $result = reset($results);
400         $this->assertEquals($user5->id, $result['id']);
402         // Empty query, will throw an exception.
403         $this->setExpectedException('moodle_exception');
404         $results = core_message_external::search_contacts('');
405     }
407     /**
408      * Test get_messages.
409      */
410     public function test_get_messages() {
411         global $CFG;
412         $this->resetAfterTest(true);
414         $this->preventResetByRollback();
415         // This mark the messages as read!.
416         $sink = $this->redirectMessages();
418         $user1 = self::getDataGenerator()->create_user();
419         $user2 = self::getDataGenerator()->create_user();
420         $user3 = self::getDataGenerator()->create_user();
422         $course = self::getDataGenerator()->create_course();
424         // Send a message from one user to another.
425         message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
426         message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
427         message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
428         message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
429         message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);
431         $this->setUser($user1);
432         // Get read conversations from user1 to user2.
433         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
434         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
435         $this->assertCount(1, $messages['messages']);
437         // Get unread conversations from user1 to user2.
438         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
439         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
440         $this->assertCount(0, $messages['messages']);
442         // Get read messages send from user1.
443         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
444         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
445         $this->assertCount(2, $messages['messages']);
447         $this->setUser($user2);
448         // Get read conversations from any user to user2.
449         $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
450         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
451         $this->assertCount(2, $messages['messages']);
453         $this->setUser($user3);
454         // Get read notifications received by user3.
455         $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
456         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
457         $this->assertCount(0, $messages['messages']);
459         // Now, create some notifications...
460         // We are creating fake notifications but based on real ones.
462         // This one omits notification = 1.
463         $eventdata = new stdClass();
464         $eventdata->modulename        = 'moodle';
465         $eventdata->component         = 'enrol_paypal';
466         $eventdata->name              = 'paypal_enrolment';
467         $eventdata->userfrom          = get_admin();
468         $eventdata->userto            = $user1;
469         $eventdata->subject           = "Moodle: PayPal payment";
470         $eventdata->fullmessage       = "Your PayPal payment is pending.";
471         $eventdata->fullmessageformat = FORMAT_PLAIN;
472         $eventdata->fullmessagehtml   = '';
473         $eventdata->smallmessage      = '';
474         message_send($eventdata);
476         $message = new stdClass();
477         $message->notification      = 1;
478         $message->component         = 'enrol_manual';
479         $message->name              = 'expiry_notification';
480         $message->userfrom          = $user2;
481         $message->userto            = $user1;
482         $message->subject           = 'Enrolment expired';
483         $message->fullmessage       = 'Enrolment expired blah blah blah';
484         $message->fullmessageformat = FORMAT_MARKDOWN;
485         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
486         $message->smallmessage      = $message->subject;
487         $message->contexturlname    = $course->fullname;
488         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
489         message_send($message);
491         $userfrom = core_user::get_noreply_user();
492         $userfrom->maildisplay = true;
493         $eventdata = new stdClass();
494         $eventdata->component         = 'moodle';
495         $eventdata->name              = 'badgecreatornotice';
496         $eventdata->userfrom          = $userfrom;
497         $eventdata->userto            = $user1;
498         $eventdata->notification      = 1;
499         $eventdata->subject           = 'New badge';
500         $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
501         $eventdata->fullmessageformat = FORMAT_PLAIN;
502         $eventdata->fullmessagehtml   = $eventdata->subject;
503         $eventdata->smallmessage      = $eventdata->subject;
504         message_send($eventdata);
506         $eventdata = new stdClass();
507         $eventdata->name             = 'submission';
508         $eventdata->component        = 'mod_feedback';
509         $eventdata->userfrom         = $user1;
510         $eventdata->userto           = $user2;
511         $eventdata->subject          = 'Feedback submitted';
512         $eventdata->fullmessage      = 'Feedback submitted from an user';
513         $eventdata->fullmessageformat = FORMAT_PLAIN;
514         $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
515         $eventdata->smallmessage     = '';
516         message_send($eventdata);
518         $this->setUser($user1);
519         // Get read notifications from any user to user1.
520         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
521         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
522         $this->assertCount(3, $messages['messages']);
524         // Get one read notifications from any user to user1.
525         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
526         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
527         $this->assertCount(1, $messages['messages']);
529         // Get unread notifications from any user to user1.
530         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
531         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
532         $this->assertCount(0, $messages['messages']);
534         // Get read both type of messages from any user to user1.
535         $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
536         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
537         $this->assertCount(4, $messages['messages']);
539         // Get read notifications from no-reply-user to user1.
540         $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
541         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
542         $this->assertCount(1, $messages['messages']);
544         // Get notifications send by user1 to any user.
545         $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
546         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
547         $this->assertCount(1, $messages['messages']);
549         // Test warnings.
550         $CFG->messaging = 0;
552         $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
553         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
554         $this->assertCount(1, $messages['warnings']);
556         // Test exceptions.
558         // Messaging disabled.
559         try {
560             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
561             $this->fail('Exception expected due messaging disabled.');
562         } catch (moodle_exception $e) {
563             $this->assertEquals('disabled', $e->errorcode);
564         }
566         $CFG->messaging = 1;
568         // Invalid users.
569         try {
570             $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
571             $this->fail('Exception expected due invalid users.');
572         } catch (moodle_exception $e) {
573             $this->assertEquals('accessdenied', $e->errorcode);
574         }
576         // Invalid user ids.
577         try {
578             $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
579             $this->fail('Exception expected due invalid users.');
580         } catch (moodle_exception $e) {
581             $this->assertEquals('invaliduser', $e->errorcode);
582         }
584         // Invalid users (permissions).
585         $this->setUser($user2);
586         try {
587             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
588             $this->fail('Exception expected due invalid user.');
589         } catch (moodle_exception $e) {
590             $this->assertEquals('accessdenied', $e->errorcode);
591         }
593     }
595     /**
596      * Test get_blocked_users.
597      */
598     public function test_get_blocked_users() {
599         $this->resetAfterTest(true);
601         $user1 = self::getDataGenerator()->create_user();
602         $userstranger = self::getDataGenerator()->create_user();
603         $useroffline1 = self::getDataGenerator()->create_user();
604         $useroffline2 = self::getDataGenerator()->create_user();
605         $userblocked = self::getDataGenerator()->create_user();
607         // Login as user1.
608         $this->setUser($user1);
609         $this->assertEquals(array(), core_message_external::create_contacts(
610             array($useroffline1->id, $useroffline2->id)));
612         // The userstranger sends a couple of messages to user1.
613         $this->send_message($userstranger, $user1, 'Hello there!');
614         $this->send_message($userstranger, $user1, 'How you goin?');
616         // The userblocked sends a message to user1.
617         // Note that this user is not blocked at this point.
618         $this->send_message($userblocked, $user1, 'Here, have some spam.');
620         // Retrieve the list of blocked users.
621         $this->setUser($user1);
622         $blockedusers = core_message_external::get_blocked_users($user1->id);
623         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
624         $this->assertCount(0, $blockedusers['users']);
626         // Block the $userblocked and retrieve again the list.
627         core_message_external::block_contacts(array($userblocked->id));
628         $blockedusers = core_message_external::get_blocked_users($user1->id);
629         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
630         $this->assertCount(1, $blockedusers['users']);
632         // Remove the $userblocked and check that the list now is empty.
633         delete_user($userblocked);
634         $blockedusers = core_message_external::get_blocked_users($user1->id);
635         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
636         $this->assertCount(0, $blockedusers['users']);
638     }
640     /**
641      * Test mark_message_read.
642      */
643     public function test_mark_message_read() {
644         $this->resetAfterTest(true);
646         $user1 = self::getDataGenerator()->create_user();
647         $user2 = self::getDataGenerator()->create_user();
648         $user3 = self::getDataGenerator()->create_user();
650         // Login as user1.
651         $this->setUser($user1);
652         $this->assertEquals(array(), core_message_external::create_contacts(
653             array($user2->id, $user3->id)));
655         // The user2 sends a couple of messages to user1.
656         $this->send_message($user2, $user1, 'Hello there!');
657         $this->send_message($user2, $user1, 'How you goin?');
658         $this->send_message($user3, $user1, 'How you goin?');
659         $this->send_message($user3, $user2, 'How you goin?');
661         // Retrieve all messages sent by user2 (they are currently unread).
662         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
664         $messageids = array();
665         foreach ($lastmessages as $m) {
666             $messageid = core_message_external::mark_message_read($m->id, time());
667             $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
668         }
670         // Retrieve all messages sent (they are currently read).
671         $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
672         $this->assertCount(2, $lastmessages);
673         $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
674         $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
676         // Retrieve all messages sent by any user (that are currently unread).
677         $lastmessages = message_get_messages($user1->id, 0, 0, false);
678         $this->assertCount(1, $lastmessages);
680         // Invalid message ids.
681         try {
682             $messageid = core_message_external::mark_message_read($messageids[0]['messageid'] * 2, time());
683             $this->fail('Exception expected due invalid messageid.');
684         } catch (dml_missing_record_exception $e) {
685             $this->assertEquals('invalidrecord', $e->errorcode);
686         }
688         // A message to a different user.
689         $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
690         $messageid = array_pop($lastmessages)->id;
691         try {
692             $messageid = core_message_external::mark_message_read($messageid, time());
693             $this->fail('Exception expected due invalid messageid.');
694         } catch (invalid_parameter_exception $e) {
695             $this->assertEquals('invalidparameter', $e->errorcode);
696         }
698     }
700     /**
701      * Test delete_message.
702      */
703     public function test_delete_message() {
704         global $DB;
705         $this->resetAfterTest(true);
707         $user1 = self::getDataGenerator()->create_user();
708         $user2 = self::getDataGenerator()->create_user();
709         $user3 = self::getDataGenerator()->create_user();
710         $user4 = self::getDataGenerator()->create_user();
712         // Login as user1.
713         $this->setUser($user1);
714         $this->assertEquals(array(), core_message_external::create_contacts(array($user2->id, $user3->id)));
716         // User user1 does not interchange messages with user3.
717         $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
718         $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
719         $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
720         $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
722         // Retrieve all messages sent by user2 (they are currently unread).
723         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
725         // Delete a message not read, as a user from.
726         $result = core_message_external::delete_message($m1to2, $user1->id, false);
727         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
728         $this->assertTrue($result['status']);
729         $this->assertCount(0, $result['warnings']);
730         $deletedmessage = $DB->get_record('message', array('id' => $m1to2));
731         $this->assertNotEquals(0, $deletedmessage->timeuserfromdeleted);
733         // Try to delete the same message again.
734         $result = core_message_external::delete_message($m1to2, $user1->id, false);
735         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
736         $this->assertFalse($result['status']);
738         // Try to delete a message that does not belong to me.
739         try {
740             $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
741             $this->fail('Exception expected due invalid messageid.');
742         } catch (moodle_exception $e) {
743             $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
744         }
746         $this->setUser($user3);
747         // Delete a message not read, as a user to.
748         $result = core_message_external::delete_message($m2to3, $user3->id, false);
749         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
750         $this->assertTrue($result['status']);
751         $this->assertCount(0, $result['warnings']);
752         $deletedmessage = $DB->get_record('message', array('id' => $m2to3));
753         $this->assertNotEquals(0, $deletedmessage->timeusertodeleted);
755         // Delete a message read.
756         $message = $DB->get_record('message', array('id' => $m3to2));
757         $messageid = message_mark_message_read($message, time());
758         $result = core_message_external::delete_message($messageid, $user3->id);
759         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
760         $this->assertTrue($result['status']);
761         $this->assertCount(0, $result['warnings']);
762         $deletedmessage = $DB->get_record('message_read', array('id' => $messageid));
763         $this->assertNotEquals(0, $deletedmessage->timeuserfromdeleted);
765         // Invalid message ids.
766         try {
767             $result = core_message_external::delete_message(-1, $user1->id);
768             $this->fail('Exception expected due invalid messageid.');
769         } catch (dml_missing_record_exception $e) {
770             $this->assertEquals('invalidrecord', $e->errorcode);
771         }
773         // Invalid user.
774         try {
775             $result = core_message_external::delete_message($m1to2, -1, false);
776             $this->fail('Exception expected due invalid user.');
777         } catch (moodle_exception $e) {
778             $this->assertEquals('invaliduser', $e->errorcode);
779         }
781         // Not active user.
782         delete_user($user2);
783         try {
784             $result = core_message_external::delete_message($m1to2, $user2->id, false);
785             $this->fail('Exception expected due invalid user.');
786         } catch (moodle_exception $e) {
787             $this->assertEquals('userdeleted', $e->errorcode);
788         }
790         // Now, as an admin, try to delete any message.
791         $this->setAdminUser();
792         $result = core_message_external::delete_message($m3to4, $user4->id, false);
793         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
794         $this->assertTrue($result['status']);
795         $this->assertCount(0, $result['warnings']);
796         $deletedmessage = $DB->get_record('message', array('id' => $m3to4));
797         $this->assertNotEquals(0, $deletedmessage->timeusertodeleted);
799     }