7454ae31590d1a3983b21905d4e3d8ccf22bd7fd
[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      * Send a fake unread notification.
68      *
69      * {@link message_send()} does not support transaction, this function will simulate a message
70      * sent from a user to another. We should stop using it once {@link message_send()} will support
71      * transactions. This is not clean at all, this is just used to add rows to the table.
72      *
73      * @param stdClass $userfrom user object of the one sending the message.
74      * @param stdClass $userto user object of the one receiving the message.
75      * @param string $message message to send.
76      * @param int $timecreated time the message was created.
77      * @return int the id of the message
78      */
79     protected function send_fake_unread_notification($userfrom, $userto, $message = 'Hello world!', $timecreated = 0) {
80         global $DB;
82         $record = new stdClass();
83         $record->useridfrom = $userfrom->id;
84         $record->useridto = $userto->id;
85         $record->notification = 1;
86         $record->subject = 'No subject';
87         $record->fullmessage = $message;
88         $record->smallmessage = $message;
89         $record->timecreated = $timecreated ? $timecreated : time();
91         return $DB->insert_record('message', $record);
92     }
94     /**
95      * Send a fake read notification.
96      *
97      * {@link message_send()} does not support transaction, this function will simulate a message
98      * sent from a user to another. We should stop using it once {@link message_send()} will support
99      * transactions. This is not clean at all, this is just used to add rows to the table.
100      *
101      * @param stdClass $userfrom user object of the one sending the message.
102      * @param stdClass $userto user object of the one receiving the message.
103      * @param string $message message to send.
104      * @param int $timecreated time the message was created.
105      * @return int the id of the message
106      */
107     protected function send_fake_read_notification($userfrom, $userto, $message = 'Hello world!', $timecreated = 0, $timeread = 0) {
108         global $DB;
110         $record = new stdClass();
111         $record->useridfrom = $userfrom->id;
112         $record->useridto = $userto->id;
113         $record->notification = 1;
114         $record->subject = 'No subject';
115         $record->fullmessage = $message;
116         $record->smallmessage = $message;
117         $record->timecreated = $timecreated ? $timecreated : time();
118         $record->timeread = $timeread ? $timeread : time();
120         return $DB->insert_record('message_read', $record);
121     }
123     /**
124      * Test send_instant_messages
125      */
126     public function test_send_instant_messages() {
128         global $DB, $USER, $CFG;
130         $this->resetAfterTest(true);
131         // Transactions used in tests, tell phpunit use alternative reset method.
132         $this->preventResetByRollback();
134         // Turn off all message processors (so nothing is really sent)
135         require_once($CFG->dirroot . '/message/lib.php');
136         $messageprocessors = get_message_processors();
137         foreach($messageprocessors as $messageprocessor) {
138             $messageprocessor->enabled = 0;
139             $DB->update_record('message_processors', $messageprocessor);
140         }
142         // Set the required capabilities by the external function
143         $contextid = context_system::instance()->id;
144         $roleid = $this->assignUserCapability('moodle/site:sendmessage', $contextid);
146         $user1 = self::getDataGenerator()->create_user();
148         // Create test message data.
149         $message1 = array();
150         $message1['touserid'] = $user1->id;
151         $message1['text'] = 'the message.';
152         $message1['clientmsgid'] = 4;
153         $messages = array($message1);
155         $sentmessages = core_message_external::send_instant_messages($messages);
157         // We need to execute the return values cleaning process to simulate the web service server.
158         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
160         $themessage = $DB->get_record('message', array('id' => $sentmessages[0]['msgid']));
162         // Confirm that the message was inserted correctly.
163         $this->assertEquals($themessage->useridfrom, $USER->id);
164         $this->assertEquals($themessage->useridto, $message1['touserid']);
165         $this->assertEquals($themessage->smallmessage, $message1['text']);
166         $this->assertEquals($sentmessages[0]['clientmsgid'], $message1['clientmsgid']);
167     }
169     /**
170      * Test create_contacts.
171      */
172     public function test_create_contacts() {
173         $this->resetAfterTest(true);
175         $user1 = self::getDataGenerator()->create_user();
176         $user2 = self::getDataGenerator()->create_user();
177         $user3 = self::getDataGenerator()->create_user();
178         $user4 = self::getDataGenerator()->create_user();
179         $user5 = self::getDataGenerator()->create_user();
180         $this->setUser($user1);
182         // Adding a contact.
183         $return = core_message_external::create_contacts(array($user2->id));
184         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
185         $this->assertEquals(array(), $return);
187         // Adding a contact who is already a contact.
188         $return = core_message_external::create_contacts(array($user2->id));
189         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
190         $this->assertEquals(array(), $return);
192         // Adding multiple contacts.
193         $return = core_message_external::create_contacts(array($user3->id, $user4->id));
194         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
195         $this->assertEquals(array(), $return);
197         // Adding a non-existing user.
198         $return = core_message_external::create_contacts(array(99999));
199         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
200         $this->assertCount(1, $return);
201         $return = array_pop($return);
202         $this->assertEquals($return['warningcode'], 'contactnotcreated');
203         $this->assertEquals($return['itemid'], 99999);
205         // Adding contacts with valid and invalid parameters.
206         $return = core_message_external::create_contacts(array($user5->id, 99999));
207         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
208         $this->assertCount(1, $return);
209         $return = array_pop($return);
210         $this->assertEquals($return['warningcode'], 'contactnotcreated');
211         $this->assertEquals($return['itemid'], 99999);
212     }
214     /**
215      * Test delete_contacts.
216      */
217     public function test_delete_contacts() {
218         $this->resetAfterTest(true);
220         $user1 = self::getDataGenerator()->create_user();
221         $user2 = self::getDataGenerator()->create_user();
222         $user3 = self::getDataGenerator()->create_user();
223         $user4 = self::getDataGenerator()->create_user();
224         $user5 = self::getDataGenerator()->create_user();
225         $user6 = self::getDataGenerator()->create_user();
226         $this->setUser($user1);
227         $this->assertEquals(array(), core_message_external::create_contacts(
228             array($user3->id, $user4->id, $user5->id, $user6->id)));
230         // Removing a non-contact.
231         $return = core_message_external::delete_contacts(array($user2->id));
232         $this->assertNull($return);
234         // Removing one contact.
235         $return = core_message_external::delete_contacts(array($user3->id));
236         $this->assertNull($return);
238         // Removing multiple contacts.
239         $return = core_message_external::delete_contacts(array($user4->id, $user5->id));
240         $this->assertNull($return);
242         // Removing contact from unexisting user.
243         $return = core_message_external::delete_contacts(array(99999));
244         $this->assertNull($return);
246         // Removing mixed valid and invalid data.
247         $return = core_message_external::delete_contacts(array($user6->id, 99999));
248         $this->assertNull($return);
249     }
251     /**
252      * Test block_contacts.
253      */
254     public function test_block_contacts() {
255         $this->resetAfterTest(true);
257         $user1 = self::getDataGenerator()->create_user();
258         $user2 = self::getDataGenerator()->create_user();
259         $user3 = self::getDataGenerator()->create_user();
260         $user4 = self::getDataGenerator()->create_user();
261         $user5 = self::getDataGenerator()->create_user();
262         $this->setUser($user1);
263         $this->assertEquals(array(), core_message_external::create_contacts(array($user3->id, $user4->id, $user5->id)));
265         // Blocking a contact.
266         $return = core_message_external::block_contacts(array($user2->id));
267         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
268         $this->assertEquals(array(), $return);
270         // Blocking a contact who is already a contact.
271         $return = core_message_external::block_contacts(array($user2->id));
272         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
273         $this->assertEquals(array(), $return);
275         // Blocking multiple contacts.
276         $return = core_message_external::block_contacts(array($user3->id, $user4->id));
277         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
278         $this->assertEquals(array(), $return);
280         // Blocking a non-existing user.
281         $return = core_message_external::block_contacts(array(99999));
282         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
283         $this->assertCount(1, $return);
284         $return = array_pop($return);
285         $this->assertEquals($return['warningcode'], 'contactnotblocked');
286         $this->assertEquals($return['itemid'], 99999);
288         // Blocking contacts with valid and invalid parameters.
289         $return = core_message_external::block_contacts(array($user5->id, 99999));
290         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
291         $this->assertCount(1, $return);
292         $return = array_pop($return);
293         $this->assertEquals($return['warningcode'], 'contactnotblocked');
294         $this->assertEquals($return['itemid'], 99999);
295     }
297     /**
298      * Test unblock_contacts.
299      */
300     public function test_unblock_contacts() {
301         $this->resetAfterTest(true);
303         $user1 = self::getDataGenerator()->create_user();
304         $user2 = self::getDataGenerator()->create_user();
305         $user3 = self::getDataGenerator()->create_user();
306         $user4 = self::getDataGenerator()->create_user();
307         $user5 = self::getDataGenerator()->create_user();
308         $user6 = self::getDataGenerator()->create_user();
309         $this->setUser($user1);
310         $this->assertEquals(array(), core_message_external::create_contacts(
311             array($user3->id, $user4->id, $user5->id, $user6->id)));
313         // Removing a non-contact.
314         $return = core_message_external::unblock_contacts(array($user2->id));
315         $this->assertNull($return);
317         // Removing one contact.
318         $return = core_message_external::unblock_contacts(array($user3->id));
319         $this->assertNull($return);
321         // Removing multiple contacts.
322         $return = core_message_external::unblock_contacts(array($user4->id, $user5->id));
323         $this->assertNull($return);
325         // Removing contact from unexisting user.
326         $return = core_message_external::unblock_contacts(array(99999));
327         $this->assertNull($return);
329         // Removing mixed valid and invalid data.
330         $return = core_message_external::unblock_contacts(array($user6->id, 99999));
331         $this->assertNull($return);
333     }
335     /**
336      * Test get_contacts.
337      */
338     public function test_get_contacts() {
339         $this->resetAfterTest(true);
341         $user1 = self::getDataGenerator()->create_user();
342         $user_stranger = self::getDataGenerator()->create_user();
343         $user_offline1 = self::getDataGenerator()->create_user();
344         $user_offline2 = self::getDataGenerator()->create_user();
345         $user_offline3 = self::getDataGenerator()->create_user();
346         $user_online = new stdClass();
347         $user_online->lastaccess = time();
348         $user_online = self::getDataGenerator()->create_user($user_online);
349         $user_blocked = self::getDataGenerator()->create_user();
350         $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
352         // Login as user1.
353         $this->setUser($user1);
354         $this->assertEquals(array(), core_message_external::create_contacts(
355             array($user_offline1->id, $user_offline2->id, $user_offline3->id, $user_online->id)));
357         // User_stranger sends a couple of messages to user1.
358         $this->send_message($user_stranger, $user1, 'Hello there!');
359         $this->send_message($user_stranger, $user1, 'How you goin?');
360         $this->send_message($user_stranger, $user1, 'Cya!');
361         $this->send_message($noreplyuser, $user1, 'I am not a real user');
363         // User_blocked sends a message to user1.
364         $this->send_message($user_blocked, $user1, 'Here, have some spam.');
366         // Retrieve the contacts of the user.
367         $this->setUser($user1);
368         $contacts = core_message_external::get_contacts();
369         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
370         $this->assertCount(3, $contacts['offline']);
371         $this->assertCount(1, $contacts['online']);
372         $this->assertCount(3, $contacts['strangers']);
373         core_message_external::block_contacts(array($user_blocked->id));
374         $contacts = core_message_external::get_contacts();
375         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
376         $this->assertCount(3, $contacts['offline']);
377         $this->assertCount(1, $contacts['online']);
378         $this->assertCount(2, $contacts['strangers']);
380         // Checking some of the fields returned.
381         $stranger = array_pop($contacts['strangers']);
383         $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
384         $this->assertEquals(1, $stranger['unread']);
386         // Check that deleted users are not returned.
387         delete_user($user_offline1);
388         delete_user($user_stranger);
389         delete_user($user_online);
390         $contacts = core_message_external::get_contacts();
391         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
392         $this->assertCount(2, $contacts['offline']);
393         $this->assertCount(0, $contacts['online']);
394         $this->assertCount(1, $contacts['strangers']);
395     }
397     /**
398      * Test search_contacts.
399      * @expectedException moodle_exception
400      */
401     public function test_search_contacts() {
402         global $DB;
403         $this->resetAfterTest(true);
405         $course1 = $this->getDataGenerator()->create_course();
406         $course2 = $this->getDataGenerator()->create_course();
408         $user1 = new stdClass();
409         $user1->firstname = 'X';
410         $user1->lastname = 'X';
411         $user1 = $this->getDataGenerator()->create_user($user1);
412         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
413         $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
415         $user2 = new stdClass();
416         $user2->firstname = 'Eric';
417         $user2->lastname = 'Cartman';
418         $user2 = self::getDataGenerator()->create_user($user2);
419         $user3 = new stdClass();
420         $user3->firstname = 'Stan';
421         $user3->lastname = 'Marsh';
422         $user3 = self::getDataGenerator()->create_user($user3);
423         self::getDataGenerator()->enrol_user($user3->id, $course1->id);
424         $user4 = new stdClass();
425         $user4->firstname = 'Kyle';
426         $user4->lastname = 'Broflovski';
427         $user4 = self::getDataGenerator()->create_user($user4);
428         $user5 = new stdClass();
429         $user5->firstname = 'Kenny';
430         $user5->lastname = 'McCormick';
431         $user5 = self::getDataGenerator()->create_user($user5);
432         self::getDataGenerator()->enrol_user($user5->id, $course2->id);
434         $this->setUser($user1);
436         $results = core_message_external::search_contacts('r');
437         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
438         $this->assertCount(5, $results); // Users 2 through 5 + admin
440         $results = core_message_external::search_contacts('r', true);
441         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
442         $this->assertCount(2, $results);
444         $results = core_message_external::search_contacts('Kyle', false);
445         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
446         $this->assertCount(1, $results);
447         $result = reset($results);
448         $this->assertEquals($user4->id, $result['id']);
450         $results = core_message_external::search_contacts('y', false);
451         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
452         $this->assertCount(2, $results);
454         $results = core_message_external::search_contacts('y', true);
455         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
456         $this->assertCount(1, $results);
457         $result = reset($results);
458         $this->assertEquals($user5->id, $result['id']);
460         // Empty query, will throw an exception.
461         $results = core_message_external::search_contacts('');
462     }
464     /**
465      * Test get_messages.
466      */
467     public function test_get_messages() {
468         global $CFG, $DB;
469         $this->resetAfterTest(true);
471         $this->preventResetByRollback();
472         // This mark the messages as read!.
473         $sink = $this->redirectMessages();
475         $user1 = self::getDataGenerator()->create_user();
476         $user2 = self::getDataGenerator()->create_user();
477         $user3 = self::getDataGenerator()->create_user();
479         $course = self::getDataGenerator()->create_course();
481         // Send a message from one user to another.
482         message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
483         message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
484         message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
485         message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
486         message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);
488         $this->setUser($user1);
489         // Get read conversations from user1 to user2.
490         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
491         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
492         $this->assertCount(1, $messages['messages']);
494         // Delete the message.
495         $message = array_shift($messages['messages']);
496         $messagetobedeleted = $DB->get_record('message_read', array('id' => $message['id']));
497         message_delete_message($messagetobedeleted, $user1->id);
499         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
500         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
501         $this->assertCount(0, $messages['messages']);
503         // Get unread conversations from user1 to user2.
504         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
505         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
506         $this->assertCount(0, $messages['messages']);
508         // Get read messages send from user1.
509         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
510         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
511         $this->assertCount(1, $messages['messages']);
513         $this->setUser($user2);
514         // Get read conversations from any user to user2.
515         $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
516         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
517         $this->assertCount(2, $messages['messages']);
519         // Conversations from user3 to user2.
520         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
521         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
522         $this->assertCount(1, $messages['messages']);
524         // Delete the message.
525         $message = array_shift($messages['messages']);
526         $messagetobedeleted = $DB->get_record('message_read', array('id' => $message['id']));
527         message_delete_message($messagetobedeleted, $user2->id);
529         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
530         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
531         $this->assertCount(0, $messages['messages']);
533         $this->setUser($user3);
534         // Get read notifications received by user3.
535         $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
536         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
537         $this->assertCount(0, $messages['messages']);
539         // Now, create some notifications...
540         // We are creating fake notifications but based on real ones.
542         // This one omits notification = 1.
543         $eventdata = new stdClass();
544         $eventdata->modulename        = 'moodle';
545         $eventdata->component         = 'enrol_paypal';
546         $eventdata->name              = 'paypal_enrolment';
547         $eventdata->userfrom          = get_admin();
548         $eventdata->userto            = $user1;
549         $eventdata->subject           = "Moodle: PayPal payment";
550         $eventdata->fullmessage       = "Your PayPal payment is pending.";
551         $eventdata->fullmessageformat = FORMAT_PLAIN;
552         $eventdata->fullmessagehtml   = '';
553         $eventdata->smallmessage      = '';
554         message_send($eventdata);
556         $message = new stdClass();
557         $message->notification      = 1;
558         $message->component         = 'enrol_manual';
559         $message->name              = 'expiry_notification';
560         $message->userfrom          = $user2;
561         $message->userto            = $user1;
562         $message->subject           = 'Enrolment expired';
563         $message->fullmessage       = 'Enrolment expired blah blah blah';
564         $message->fullmessageformat = FORMAT_MARKDOWN;
565         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
566         $message->smallmessage      = $message->subject;
567         $message->contexturlname    = $course->fullname;
568         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
569         message_send($message);
571         $userfrom = core_user::get_noreply_user();
572         $userfrom->maildisplay = true;
573         $eventdata = new stdClass();
574         $eventdata->component         = 'moodle';
575         $eventdata->name              = 'badgecreatornotice';
576         $eventdata->userfrom          = $userfrom;
577         $eventdata->userto            = $user1;
578         $eventdata->notification      = 1;
579         $eventdata->subject           = 'New badge';
580         $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
581         $eventdata->fullmessageformat = FORMAT_PLAIN;
582         $eventdata->fullmessagehtml   = $eventdata->subject;
583         $eventdata->smallmessage      = $eventdata->subject;
584         message_send($eventdata);
586         $eventdata = new stdClass();
587         $eventdata->name             = 'submission';
588         $eventdata->component        = 'mod_feedback';
589         $eventdata->userfrom         = $user1;
590         $eventdata->userto           = $user2;
591         $eventdata->subject          = 'Feedback submitted';
592         $eventdata->fullmessage      = 'Feedback submitted from an user';
593         $eventdata->fullmessageformat = FORMAT_PLAIN;
594         $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
595         $eventdata->smallmessage     = '';
596         message_send($eventdata);
598         $this->setUser($user1);
599         // Get read notifications from any user to user1.
600         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
601         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
602         $this->assertCount(3, $messages['messages']);
604         // Get one read notifications from any user to user1.
605         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
606         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
607         $this->assertCount(1, $messages['messages']);
609         // Get unread notifications from any user to user1.
610         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
611         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
612         $this->assertCount(0, $messages['messages']);
614         // Get read both type of messages from any user to user1.
615         $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
616         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
617         $this->assertCount(4, $messages['messages']);
619         // Get read notifications from no-reply-user to user1.
620         $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
621         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
622         $this->assertCount(1, $messages['messages']);
624         // Get notifications send by user1 to any user.
625         $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
626         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
627         $this->assertCount(1, $messages['messages']);
629         // Test warnings.
630         $CFG->messaging = 0;
632         $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
633         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
634         $this->assertCount(1, $messages['warnings']);
636         // Test exceptions.
638         // Messaging disabled.
639         try {
640             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
641             $this->fail('Exception expected due messaging disabled.');
642         } catch (moodle_exception $e) {
643             $this->assertEquals('disabled', $e->errorcode);
644         }
646         $CFG->messaging = 1;
648         // Invalid users.
649         try {
650             $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
651             $this->fail('Exception expected due invalid users.');
652         } catch (moodle_exception $e) {
653             $this->assertEquals('accessdenied', $e->errorcode);
654         }
656         // Invalid user ids.
657         try {
658             $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
659             $this->fail('Exception expected due invalid users.');
660         } catch (moodle_exception $e) {
661             $this->assertEquals('invaliduser', $e->errorcode);
662         }
664         // Invalid users (permissions).
665         $this->setUser($user2);
666         try {
667             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
668             $this->fail('Exception expected due invalid user.');
669         } catch (moodle_exception $e) {
670             $this->assertEquals('accessdenied', $e->errorcode);
671         }
673     }
675     /**
676      * Test get_blocked_users.
677      */
678     public function test_get_blocked_users() {
679         $this->resetAfterTest(true);
681         $user1 = self::getDataGenerator()->create_user();
682         $userstranger = self::getDataGenerator()->create_user();
683         $useroffline1 = self::getDataGenerator()->create_user();
684         $useroffline2 = self::getDataGenerator()->create_user();
685         $userblocked = self::getDataGenerator()->create_user();
687         // Login as user1.
688         $this->setUser($user1);
689         $this->assertEquals(array(), core_message_external::create_contacts(
690             array($useroffline1->id, $useroffline2->id)));
692         // The userstranger sends a couple of messages to user1.
693         $this->send_message($userstranger, $user1, 'Hello there!');
694         $this->send_message($userstranger, $user1, 'How you goin?');
696         // The userblocked sends a message to user1.
697         // Note that this user is not blocked at this point.
698         $this->send_message($userblocked, $user1, 'Here, have some spam.');
700         // Retrieve the list of blocked users.
701         $this->setUser($user1);
702         $blockedusers = core_message_external::get_blocked_users($user1->id);
703         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
704         $this->assertCount(0, $blockedusers['users']);
706         // Block the $userblocked and retrieve again the list.
707         core_message_external::block_contacts(array($userblocked->id));
708         $blockedusers = core_message_external::get_blocked_users($user1->id);
709         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
710         $this->assertCount(1, $blockedusers['users']);
712         // Remove the $userblocked and check that the list now is empty.
713         delete_user($userblocked);
714         $blockedusers = core_message_external::get_blocked_users($user1->id);
715         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
716         $this->assertCount(0, $blockedusers['users']);
718     }
720     /**
721      * Test mark_message_read.
722      */
723     public function test_mark_message_read() {
724         $this->resetAfterTest(true);
726         $user1 = self::getDataGenerator()->create_user();
727         $user2 = self::getDataGenerator()->create_user();
728         $user3 = self::getDataGenerator()->create_user();
730         // Login as user1.
731         $this->setUser($user1);
732         $this->assertEquals(array(), core_message_external::create_contacts(
733             array($user2->id, $user3->id)));
735         // The user2 sends a couple of messages to user1.
736         $this->send_message($user2, $user1, 'Hello there!');
737         $this->send_message($user2, $user1, 'How you goin?');
738         $this->send_message($user3, $user1, 'How you goin?');
739         $this->send_message($user3, $user2, 'How you goin?');
741         // Retrieve all messages sent by user2 (they are currently unread).
742         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
744         $messageids = array();
745         foreach ($lastmessages as $m) {
746             $messageid = core_message_external::mark_message_read($m->id, time());
747             $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
748         }
750         // Retrieve all messages sent (they are currently read).
751         $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
752         $this->assertCount(2, $lastmessages);
753         $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
754         $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
756         // Retrieve all messages sent by any user (that are currently unread).
757         $lastmessages = message_get_messages($user1->id, 0, 0, false);
758         $this->assertCount(1, $lastmessages);
760         // Invalid message ids.
761         try {
762             $messageid = core_message_external::mark_message_read($messageids[0]['messageid'] * 2, time());
763             $this->fail('Exception expected due invalid messageid.');
764         } catch (dml_missing_record_exception $e) {
765             $this->assertEquals('invalidrecord', $e->errorcode);
766         }
768         // A message to a different user.
769         $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
770         $messageid = array_pop($lastmessages)->id;
771         try {
772             $messageid = core_message_external::mark_message_read($messageid, time());
773             $this->fail('Exception expected due invalid messageid.');
774         } catch (invalid_parameter_exception $e) {
775             $this->assertEquals('invalidparameter', $e->errorcode);
776         }
778     }
780     /**
781      * Test delete_message.
782      */
783     public function test_delete_message() {
784         global $DB;
785         $this->resetAfterTest(true);
787         $user1 = self::getDataGenerator()->create_user();
788         $user2 = self::getDataGenerator()->create_user();
789         $user3 = self::getDataGenerator()->create_user();
790         $user4 = self::getDataGenerator()->create_user();
792         // Login as user1.
793         $this->setUser($user1);
794         $this->assertEquals(array(), core_message_external::create_contacts(array($user2->id, $user3->id)));
796         // User user1 does not interchange messages with user3.
797         $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
798         $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
799         $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
800         $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
802         // Retrieve all messages sent by user2 (they are currently unread).
803         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
805         // Delete a message not read, as a user from.
806         $result = core_message_external::delete_message($m1to2, $user1->id, false);
807         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
808         $this->assertTrue($result['status']);
809         $this->assertCount(0, $result['warnings']);
810         $deletedmessage = $DB->get_record('message', array('id' => $m1to2));
811         $this->assertNotEquals(0, $deletedmessage->timeuserfromdeleted);
813         // Try to delete the same message again.
814         $result = core_message_external::delete_message($m1to2, $user1->id, false);
815         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
816         $this->assertFalse($result['status']);
818         // Try to delete a message that does not belong to me.
819         try {
820             $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
821             $this->fail('Exception expected due invalid messageid.');
822         } catch (moodle_exception $e) {
823             $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
824         }
826         $this->setUser($user3);
827         // Delete a message not read, as a user to.
828         $result = core_message_external::delete_message($m2to3, $user3->id, false);
829         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
830         $this->assertTrue($result['status']);
831         $this->assertCount(0, $result['warnings']);
832         $deletedmessage = $DB->get_record('message', array('id' => $m2to3));
833         $this->assertNotEquals(0, $deletedmessage->timeusertodeleted);
835         // Delete a message read.
836         $message = $DB->get_record('message', array('id' => $m3to2));
837         $messageid = message_mark_message_read($message, time());
838         $result = core_message_external::delete_message($messageid, $user3->id);
839         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
840         $this->assertTrue($result['status']);
841         $this->assertCount(0, $result['warnings']);
842         $deletedmessage = $DB->get_record('message_read', array('id' => $messageid));
843         $this->assertNotEquals(0, $deletedmessage->timeuserfromdeleted);
845         // Invalid message ids.
846         try {
847             $result = core_message_external::delete_message(-1, $user1->id);
848             $this->fail('Exception expected due invalid messageid.');
849         } catch (dml_missing_record_exception $e) {
850             $this->assertEquals('invalidrecord', $e->errorcode);
851         }
853         // Invalid user.
854         try {
855             $result = core_message_external::delete_message($m1to2, -1, false);
856             $this->fail('Exception expected due invalid user.');
857         } catch (moodle_exception $e) {
858             $this->assertEquals('invaliduser', $e->errorcode);
859         }
861         // Not active user.
862         delete_user($user2);
863         try {
864             $result = core_message_external::delete_message($m1to2, $user2->id, false);
865             $this->fail('Exception expected due invalid user.');
866         } catch (moodle_exception $e) {
867             $this->assertEquals('userdeleted', $e->errorcode);
868         }
870         // Now, as an admin, try to delete any message.
871         $this->setAdminUser();
872         $result = core_message_external::delete_message($m3to4, $user4->id, false);
873         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
874         $this->assertTrue($result['status']);
875         $this->assertCount(0, $result['warnings']);
876         $deletedmessage = $DB->get_record('message', array('id' => $m3to4));
877         $this->assertNotEquals(0, $deletedmessage->timeusertodeleted);
879     }
881     public function test_get_notifications_no_user_exception() {
882         $this->resetAfterTest(true);
884         $this->setExpectedException('moodle_exception');
885         $result = core_message_external::get_notifications(-2132131, 0, '', false, false, true, false, 0, 0);
886     }
888     public function test_get_notifications_access_denied_exception() {
889         $this->resetAfterTest(true);
891         $sender = $this->getDataGenerator()->create_user();
892         $user = $this->getDataGenerator()->create_user();
894         $this->setUser($user);
895         $this->setExpectedException('moodle_exception');
896         $result = core_message_external::get_notifications($sender->id, 0, '', false, false, true, false, 0, 0);
897     }
899     public function test_get_notifications_as_recipient() {
900         $this->resetAfterTest(true);
902         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Sendy', 'lastname' => 'Sender'));
903         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Recipy', 'lastname' => 'Recipient'));
905         $notificationids = array(
906             $this->send_fake_unread_notification($sender, $recipient),
907             $this->send_fake_unread_notification($sender, $recipient),
908             $this->send_fake_read_notification($sender, $recipient),
909             $this->send_fake_read_notification($sender, $recipient),
910         );
912         // Confirm that admin has super powers to retrieve any notifications.
913         $this->setAdminUser();
914         $result = core_message_external::get_notifications($recipient->id, 0, '', false, false, true, false, 0, 0);
915         $this->assertCount(4, $result['notifications']);
917         $this->setUser($recipient);
918         $result = core_message_external::get_notifications($recipient->id, 0, '', false, false, true, false, 0, 0);
919         $this->assertCount(4, $result['notifications']);
921         $result = core_message_external::get_notifications($recipient->id, 0, MESSAGE_UNREAD, false, true, true, false, 0, 0);
922         $this->assertCount(2, $result['notifications']);
923         $this->assertObjectHasAttribute('userfromfullname', $result['notifications'][0]);
924         $this->assertObjectNotHasAttribute('usertofullname', $result['notifications'][0]);
925         $this->assertObjectHasAttribute('userfromfullname', $result['notifications'][1]);
926         $this->assertObjectNotHasAttribute('usertofullname', $result['notifications'][1]);
928         $result = core_message_external::get_notifications($recipient->id, 0, MESSAGE_UNREAD, true, true, true, false, 0, 0);
929         $this->assertCount(2, $result['notifications']);
930         $this->assertObjectHasAttribute('userfromfullname', $result['notifications'][0]);
931         $this->assertObjectHasAttribute('usertofullname', $result['notifications'][0]);
932         $this->assertObjectHasAttribute('userfromfullname', $result['notifications'][1]);
933         $this->assertObjectHasAttribute('usertofullname', $result['notifications'][1]);
935         $result = core_message_external::get_notifications($recipient->id, 0, MESSAGE_UNREAD, true, true, true, true, 0, 0);
936         $this->assertCount(2, $result['notifications']);
937         $this->assertEquals(0, $result['unreadcount']);
939         $result = core_message_external::get_notifications($recipient->id, 0, MESSAGE_UNREAD, true, true, true, true, 0, 0);
940         $this->assertCount(0, $result['notifications']);
942         $result = core_message_external::get_notifications($recipient->id, 0, MESSAGE_READ, true, true, true, true, 0, 0);
943         $this->assertCount(4, $result['notifications']);
944     }
946     public function test_get_notification_limit_offset() {
947         $this->resetAfterTest(true);
949         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Sendy', 'lastname' => 'Sender'));
950         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Recipy', 'lastname' => 'Recipient'));
952         $this->setUser($recipient);
954         $notificationids = array(
955             $this->send_fake_unread_notification($sender, $recipient, 'Notification', 1),
956             $this->send_fake_unread_notification($sender, $recipient, 'Notification', 2),
957             $this->send_fake_unread_notification($sender, $recipient, 'Notification', 3),
958             $this->send_fake_unread_notification($sender, $recipient, 'Notification', 4),
959             $this->send_fake_read_notification($sender, $recipient, 'Notification', 5),
960             $this->send_fake_read_notification($sender, $recipient, 'Notification', 6),
961             $this->send_fake_read_notification($sender, $recipient, 'Notification', 7),
962             $this->send_fake_read_notification($sender, $recipient, 'Notification', 8),
963         );
965         $result = core_message_external::get_notifications($recipient->id, 0, '', false, false, true, false, 2, 0);
967         $this->assertEquals($result['notifications'][0]->id, $notificationids[7]);
968         $this->assertEquals($result['notifications'][1]->id, $notificationids[6]);
970         $result = core_message_external::get_notifications($recipient->id, 0, '', false, false, true, false, 2, 2);
972         $this->assertEquals($result['notifications'][0]->id, $notificationids[5]);
973         $this->assertEquals($result['notifications'][1]->id, $notificationids[4]);
974     }
976     public function test_mark_all_notifications_as_read_invalid_user_exception() {
977         $this->resetAfterTest(true);
979         $this->setExpectedException('moodle_exception');
980         $result = core_message_external::mark_all_notifications_as_read(-2132131, 0);
981     }
983     public function test_mark_all_notifications_as_read_access_denied_exception() {
984         $this->resetAfterTest(true);
986         $sender = $this->getDataGenerator()->create_user();
987         $user = $this->getDataGenerator()->create_user();
989         $this->setUser($user);
990         $this->setExpectedException('moodle_exception');
991         $result = core_message_external::mark_all_notifications_as_read($sender->id, 0);
992     }
994     public function test_mark_all_notifications_as_read_missing_from_user_exception() {
995         $this->resetAfterTest(true);
997         $sender = $this->getDataGenerator()->create_user();
999         $this->setUser($sender);
1000         $this->setExpectedException('moodle_exception');
1001         $result = core_message_external::mark_all_notifications_as_read($sender->id, 99999);
1002     }
1004     public function test_mark_all_notifications_as_read() {
1005         $this->resetAfterTest(true);
1007         $sender1 = $this->getDataGenerator()->create_user();
1008         $sender2 = $this->getDataGenerator()->create_user();
1009         $sender3 = $this->getDataGenerator()->create_user();
1010         $recipient = $this->getDataGenerator()->create_user();
1012         $this->setUser($recipient);
1014         $notificationids = array(
1015             $this->send_fake_unread_notification($sender1, $recipient, 'Notification', 1),
1016             $this->send_fake_unread_notification($sender1, $recipient, 'Notification', 2),
1017             $this->send_fake_unread_notification($sender2, $recipient, 'Notification', 3),
1018             $this->send_fake_unread_notification($sender2, $recipient, 'Notification', 4),
1019             $this->send_fake_unread_notification($sender3, $recipient, 'Notification', 5),
1020             $this->send_fake_unread_notification($sender3, $recipient, 'Notification', 6),
1021         );
1023         core_message_external::mark_all_notifications_as_read($recipient->id, $sender1->id);
1024         $readresult = core_message_external::get_notifications($recipient->id, 0, 'read', false, false, true, false, 0, 0);
1025         $unreadresult = core_message_external::get_notifications($recipient->id, 0, 'unread', false, false, true, false, 0, 0);
1027         $this->assertCount(2, $readresult['notifications']);
1028         $this->assertCount(4, $unreadresult['notifications']);
1030         core_message_external::mark_all_notifications_as_read($recipient->id, 0);
1031         $readresult = core_message_external::get_notifications($recipient->id, 0, 'read', false, false, true, false, 0, 0);
1032         $unreadresult = core_message_external::get_notifications($recipient->id, 0, 'unread', false, false, true, false, 0, 0);
1034         $this->assertCount(6, $readresult['notifications']);
1035         $this->assertCount(0, $unreadresult['notifications']);
1036     }
1038     public function test_get_unread_notification_count_invalid_user_exception() {
1039         $this->resetAfterTest(true);
1041         $this->setExpectedException('moodle_exception');
1042         $result = core_message_external::get_unread_notification_count(-2132131, 0);
1043     }
1045     public function test_get_unread_notification_count_access_denied_exception() {
1046         $this->resetAfterTest(true);
1048         $sender = $this->getDataGenerator()->create_user();
1049         $user = $this->getDataGenerator()->create_user();
1051         $this->setUser($user);
1052         $this->setExpectedException('moodle_exception');
1053         $result = core_message_external::get_unread_notification_count($sender->id, 0);
1054     }
1056     public function test_get_unread_notification_count_missing_from_user_exception() {
1057         $this->resetAfterTest(true);
1059         $sender = $this->getDataGenerator()->create_user();
1061         $this->setUser($sender);
1062         $this->setExpectedException('moodle_exception');
1063         $result = core_message_external::get_unread_notification_count($sender->id, 99999);
1064     }
1066     public function test_get_unread_notification_count() {
1067         $this->resetAfterTest(true);
1069         $sender1 = $this->getDataGenerator()->create_user();
1070         $sender2 = $this->getDataGenerator()->create_user();
1071         $sender3 = $this->getDataGenerator()->create_user();
1072         $recipient = $this->getDataGenerator()->create_user();
1074         $this->setUser($recipient);
1076         $notificationids = array(
1077             $this->send_fake_unread_notification($sender1, $recipient, 'Notification', 1),
1078             $this->send_fake_unread_notification($sender1, $recipient, 'Notification', 2),
1079             $this->send_fake_unread_notification($sender2, $recipient, 'Notification', 3),
1080             $this->send_fake_unread_notification($sender2, $recipient, 'Notification', 4),
1081             $this->send_fake_unread_notification($sender3, $recipient, 'Notification', 5),
1082             $this->send_fake_unread_notification($sender3, $recipient, 'Notification', 6),
1083         );
1085         $count = core_message_external::get_unread_notification_count($recipient->id, $sender1->id);
1086         $this->assertEquals($count, 2);
1088         $count = core_message_external::get_unread_notification_count($recipient->id, 0);
1089         $this->assertEquals($count, 6);
1090     }