e2bf202bf68bd46304994321f59f6d26f16319d5
[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      * @expectedException moodle_exception
343      */
344     public function test_search_contacts() {
345         global $DB;
346         $this->resetAfterTest(true);
348         $course1 = $this->getDataGenerator()->create_course();
349         $course2 = $this->getDataGenerator()->create_course();
351         $user1 = new stdClass();
352         $user1->firstname = 'X';
353         $user1->lastname = 'X';
354         $user1 = $this->getDataGenerator()->create_user($user1);
355         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
356         $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
358         $user2 = new stdClass();
359         $user2->firstname = 'Eric';
360         $user2->lastname = 'Cartman';
361         $user2 = self::getDataGenerator()->create_user($user2);
362         $user3 = new stdClass();
363         $user3->firstname = 'Stan';
364         $user3->lastname = 'Marsh';
365         $user3 = self::getDataGenerator()->create_user($user3);
366         self::getDataGenerator()->enrol_user($user3->id, $course1->id);
367         $user4 = new stdClass();
368         $user4->firstname = 'Kyle';
369         $user4->lastname = 'Broflovski';
370         $user4 = self::getDataGenerator()->create_user($user4);
371         $user5 = new stdClass();
372         $user5->firstname = 'Kenny';
373         $user5->lastname = 'McCormick';
374         $user5 = self::getDataGenerator()->create_user($user5);
375         self::getDataGenerator()->enrol_user($user5->id, $course2->id);
377         $this->setUser($user1);
379         $results = core_message_external::search_contacts('r');
380         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
381         $this->assertCount(5, $results); // Users 2 through 5 + admin
383         $results = core_message_external::search_contacts('r', true);
384         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
385         $this->assertCount(2, $results);
387         $results = core_message_external::search_contacts('Kyle', false);
388         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
389         $this->assertCount(1, $results);
390         $result = reset($results);
391         $this->assertEquals($user4->id, $result['id']);
393         $results = core_message_external::search_contacts('y', false);
394         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
395         $this->assertCount(2, $results);
397         $results = core_message_external::search_contacts('y', true);
398         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
399         $this->assertCount(1, $results);
400         $result = reset($results);
401         $this->assertEquals($user5->id, $result['id']);
403         // Empty query, will throw an exception.
404         $results = core_message_external::search_contacts('');
405     }
407     /**
408      * Test get_messages.
409      */
410     public function test_get_messages() {
411         global $CFG, $DB;
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         // Delete the message.
438         $message = array_shift($messages['messages']);
439         $messagetobedeleted = $DB->get_record('message_read', array('id' => $message['id']));
440         message_delete_message($messagetobedeleted, $user1->id);
442         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
443         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
444         $this->assertCount(0, $messages['messages']);
446         // Get unread conversations from user1 to user2.
447         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
448         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
449         $this->assertCount(0, $messages['messages']);
451         // Get read messages send from user1.
452         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
453         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
454         $this->assertCount(1, $messages['messages']);
456         $this->setUser($user2);
457         // Get read conversations from any user to user2.
458         $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
459         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
460         $this->assertCount(2, $messages['messages']);
462         // Conversations from user3 to user2.
463         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
464         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
465         $this->assertCount(1, $messages['messages']);
467         // Delete the message.
468         $message = array_shift($messages['messages']);
469         $messagetobedeleted = $DB->get_record('message_read', array('id' => $message['id']));
470         message_delete_message($messagetobedeleted, $user2->id);
472         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
473         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
474         $this->assertCount(0, $messages['messages']);
476         $this->setUser($user3);
477         // Get read notifications received by user3.
478         $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
479         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
480         $this->assertCount(0, $messages['messages']);
482         // Now, create some notifications...
483         // We are creating fake notifications but based on real ones.
485         // This one omits notification = 1.
486         $eventdata = new stdClass();
487         $eventdata->modulename        = 'moodle';
488         $eventdata->component         = 'enrol_paypal';
489         $eventdata->name              = 'paypal_enrolment';
490         $eventdata->userfrom          = get_admin();
491         $eventdata->userto            = $user1;
492         $eventdata->subject           = "Moodle: PayPal payment";
493         $eventdata->fullmessage       = "Your PayPal payment is pending.";
494         $eventdata->fullmessageformat = FORMAT_PLAIN;
495         $eventdata->fullmessagehtml   = '';
496         $eventdata->smallmessage      = '';
497         message_send($eventdata);
499         $message = new stdClass();
500         $message->notification      = 1;
501         $message->component         = 'enrol_manual';
502         $message->name              = 'expiry_notification';
503         $message->userfrom          = $user2;
504         $message->userto            = $user1;
505         $message->subject           = 'Enrolment expired';
506         $message->fullmessage       = 'Enrolment expired blah blah blah';
507         $message->fullmessageformat = FORMAT_MARKDOWN;
508         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
509         $message->smallmessage      = $message->subject;
510         $message->contexturlname    = $course->fullname;
511         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
512         message_send($message);
514         $userfrom = core_user::get_noreply_user();
515         $userfrom->maildisplay = true;
516         $eventdata = new stdClass();
517         $eventdata->component         = 'moodle';
518         $eventdata->name              = 'badgecreatornotice';
519         $eventdata->userfrom          = $userfrom;
520         $eventdata->userto            = $user1;
521         $eventdata->notification      = 1;
522         $eventdata->subject           = 'New badge';
523         $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
524         $eventdata->fullmessageformat = FORMAT_PLAIN;
525         $eventdata->fullmessagehtml   = $eventdata->subject;
526         $eventdata->smallmessage      = $eventdata->subject;
527         message_send($eventdata);
529         $eventdata = new stdClass();
530         $eventdata->name             = 'submission';
531         $eventdata->component        = 'mod_feedback';
532         $eventdata->userfrom         = $user1;
533         $eventdata->userto           = $user2;
534         $eventdata->subject          = 'Feedback submitted';
535         $eventdata->fullmessage      = 'Feedback submitted from an user';
536         $eventdata->fullmessageformat = FORMAT_PLAIN;
537         $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
538         $eventdata->smallmessage     = '';
539         message_send($eventdata);
541         $this->setUser($user1);
542         // Get read notifications from any user to user1.
543         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
544         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
545         $this->assertCount(3, $messages['messages']);
547         // Get one read notifications from any user to user1.
548         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
549         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
550         $this->assertCount(1, $messages['messages']);
552         // Get unread notifications from any user to user1.
553         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
554         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
555         $this->assertCount(0, $messages['messages']);
557         // Get read both type of messages from any user to user1.
558         $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
559         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
560         $this->assertCount(4, $messages['messages']);
562         // Get read notifications from no-reply-user to user1.
563         $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
564         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
565         $this->assertCount(1, $messages['messages']);
567         // Get notifications send by user1 to any user.
568         $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
569         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
570         $this->assertCount(1, $messages['messages']);
572         // Test warnings.
573         $CFG->messaging = 0;
575         $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
576         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
577         $this->assertCount(1, $messages['warnings']);
579         // Test exceptions.
581         // Messaging disabled.
582         try {
583             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
584             $this->fail('Exception expected due messaging disabled.');
585         } catch (moodle_exception $e) {
586             $this->assertEquals('disabled', $e->errorcode);
587         }
589         $CFG->messaging = 1;
591         // Invalid users.
592         try {
593             $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
594             $this->fail('Exception expected due invalid users.');
595         } catch (moodle_exception $e) {
596             $this->assertEquals('accessdenied', $e->errorcode);
597         }
599         // Invalid user ids.
600         try {
601             $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
602             $this->fail('Exception expected due invalid users.');
603         } catch (moodle_exception $e) {
604             $this->assertEquals('invaliduser', $e->errorcode);
605         }
607         // Invalid users (permissions).
608         $this->setUser($user2);
609         try {
610             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
611             $this->fail('Exception expected due invalid user.');
612         } catch (moodle_exception $e) {
613             $this->assertEquals('accessdenied', $e->errorcode);
614         }
616     }
618     /**
619      * Test get_blocked_users.
620      */
621     public function test_get_blocked_users() {
622         $this->resetAfterTest(true);
624         $user1 = self::getDataGenerator()->create_user();
625         $userstranger = self::getDataGenerator()->create_user();
626         $useroffline1 = self::getDataGenerator()->create_user();
627         $useroffline2 = self::getDataGenerator()->create_user();
628         $userblocked = self::getDataGenerator()->create_user();
630         // Login as user1.
631         $this->setUser($user1);
632         $this->assertEquals(array(), core_message_external::create_contacts(
633             array($useroffline1->id, $useroffline2->id)));
635         // The userstranger sends a couple of messages to user1.
636         $this->send_message($userstranger, $user1, 'Hello there!');
637         $this->send_message($userstranger, $user1, 'How you goin?');
639         // The userblocked sends a message to user1.
640         // Note that this user is not blocked at this point.
641         $this->send_message($userblocked, $user1, 'Here, have some spam.');
643         // Retrieve the list of blocked users.
644         $this->setUser($user1);
645         $blockedusers = core_message_external::get_blocked_users($user1->id);
646         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
647         $this->assertCount(0, $blockedusers['users']);
649         // Block the $userblocked and retrieve again the list.
650         core_message_external::block_contacts(array($userblocked->id));
651         $blockedusers = core_message_external::get_blocked_users($user1->id);
652         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
653         $this->assertCount(1, $blockedusers['users']);
655         // Remove the $userblocked and check that the list now is empty.
656         delete_user($userblocked);
657         $blockedusers = core_message_external::get_blocked_users($user1->id);
658         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
659         $this->assertCount(0, $blockedusers['users']);
661     }
663     /**
664      * Test mark_message_read.
665      */
666     public function test_mark_message_read() {
667         $this->resetAfterTest(true);
669         $user1 = self::getDataGenerator()->create_user();
670         $user2 = self::getDataGenerator()->create_user();
671         $user3 = self::getDataGenerator()->create_user();
673         // Login as user1.
674         $this->setUser($user1);
675         $this->assertEquals(array(), core_message_external::create_contacts(
676             array($user2->id, $user3->id)));
678         // The user2 sends a couple of messages to user1.
679         $this->send_message($user2, $user1, 'Hello there!');
680         $this->send_message($user2, $user1, 'How you goin?');
681         $this->send_message($user3, $user1, 'How you goin?');
682         $this->send_message($user3, $user2, 'How you goin?');
684         // Retrieve all messages sent by user2 (they are currently unread).
685         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
687         $messageids = array();
688         foreach ($lastmessages as $m) {
689             $messageid = core_message_external::mark_message_read($m->id, time());
690             $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
691         }
693         // Retrieve all messages sent (they are currently read).
694         $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
695         $this->assertCount(2, $lastmessages);
696         $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
697         $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
699         // Retrieve all messages sent by any user (that are currently unread).
700         $lastmessages = message_get_messages($user1->id, 0, 0, false);
701         $this->assertCount(1, $lastmessages);
703         // Invalid message ids.
704         try {
705             $messageid = core_message_external::mark_message_read($messageids[0]['messageid'] * 2, time());
706             $this->fail('Exception expected due invalid messageid.');
707         } catch (dml_missing_record_exception $e) {
708             $this->assertEquals('invalidrecord', $e->errorcode);
709         }
711         // A message to a different user.
712         $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
713         $messageid = array_pop($lastmessages)->id;
714         try {
715             $messageid = core_message_external::mark_message_read($messageid, time());
716             $this->fail('Exception expected due invalid messageid.');
717         } catch (invalid_parameter_exception $e) {
718             $this->assertEquals('invalidparameter', $e->errorcode);
719         }
721     }
723     /**
724      * Test delete_message.
725      */
726     public function test_delete_message() {
727         global $DB;
728         $this->resetAfterTest(true);
730         $user1 = self::getDataGenerator()->create_user();
731         $user2 = self::getDataGenerator()->create_user();
732         $user3 = self::getDataGenerator()->create_user();
733         $user4 = self::getDataGenerator()->create_user();
735         // Login as user1.
736         $this->setUser($user1);
737         $this->assertEquals(array(), core_message_external::create_contacts(array($user2->id, $user3->id)));
739         // User user1 does not interchange messages with user3.
740         $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
741         $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
742         $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
743         $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
745         // Retrieve all messages sent by user2 (they are currently unread).
746         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
748         // Delete a message not read, as a user from.
749         $result = core_message_external::delete_message($m1to2, $user1->id, false);
750         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
751         $this->assertTrue($result['status']);
752         $this->assertCount(0, $result['warnings']);
753         $deletedmessage = $DB->get_record('message', array('id' => $m1to2));
754         $this->assertNotEquals(0, $deletedmessage->timeuserfromdeleted);
756         // Try to delete the same message again.
757         $result = core_message_external::delete_message($m1to2, $user1->id, false);
758         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
759         $this->assertFalse($result['status']);
761         // Try to delete a message that does not belong to me.
762         try {
763             $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
764             $this->fail('Exception expected due invalid messageid.');
765         } catch (moodle_exception $e) {
766             $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
767         }
769         $this->setUser($user3);
770         // Delete a message not read, as a user to.
771         $result = core_message_external::delete_message($m2to3, $user3->id, false);
772         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
773         $this->assertTrue($result['status']);
774         $this->assertCount(0, $result['warnings']);
775         $deletedmessage = $DB->get_record('message', array('id' => $m2to3));
776         $this->assertNotEquals(0, $deletedmessage->timeusertodeleted);
778         // Delete a message read.
779         $message = $DB->get_record('message', array('id' => $m3to2));
780         $messageid = message_mark_message_read($message, time());
781         $result = core_message_external::delete_message($messageid, $user3->id);
782         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
783         $this->assertTrue($result['status']);
784         $this->assertCount(0, $result['warnings']);
785         $deletedmessage = $DB->get_record('message_read', array('id' => $messageid));
786         $this->assertNotEquals(0, $deletedmessage->timeuserfromdeleted);
788         // Invalid message ids.
789         try {
790             $result = core_message_external::delete_message(-1, $user1->id);
791             $this->fail('Exception expected due invalid messageid.');
792         } catch (dml_missing_record_exception $e) {
793             $this->assertEquals('invalidrecord', $e->errorcode);
794         }
796         // Invalid user.
797         try {
798             $result = core_message_external::delete_message($m1to2, -1, false);
799             $this->fail('Exception expected due invalid user.');
800         } catch (moodle_exception $e) {
801             $this->assertEquals('invaliduser', $e->errorcode);
802         }
804         // Not active user.
805         delete_user($user2);
806         try {
807             $result = core_message_external::delete_message($m1to2, $user2->id, false);
808             $this->fail('Exception expected due invalid user.');
809         } catch (moodle_exception $e) {
810             $this->assertEquals('userdeleted', $e->errorcode);
811         }
813         // Now, as an admin, try to delete any message.
814         $this->setAdminUser();
815         $result = core_message_external::delete_message($m3to4, $user4->id, false);
816         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
817         $this->assertTrue($result['status']);
818         $this->assertCount(0, $result['warnings']);
819         $deletedmessage = $DB->get_record('message', array('id' => $m3to4));
820         $this->assertNotEquals(0, $deletedmessage->timeusertodeleted);
822     }