MDL-58650 core_message: always use 'popup' processor for messages
[moodle.git] / lib / tests / messagelib_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  * Tests for messagelib.php.
19  *
20  * @package    core_message
21  * @category   phpunit
22  * @copyright  2012 The Open Universtiy
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 class core_messagelib_testcase extends advanced_testcase {
30     public function test_message_provider_disabled() {
31         $this->resetAfterTest();
32         $this->preventResetByRollback();
34         // Disable instantmessage provider.
35         $disableprovidersetting = 'moodle_instantmessage_disable';
36         set_config($disableprovidersetting, 1, 'message');
37         $preferences = get_message_output_default_preferences();
38         $this->assertTrue($preferences->$disableprovidersetting == 1);
40         $message = new \core\message\message();
41         $message->courseid          = 1;
42         $message->component         = 'moodle';
43         $message->name              = 'instantmessage';
44         $message->userfrom          = get_admin();
45         $message->userto            = $this->getDataGenerator()->create_user();;
46         $message->subject           = 'message subject 1';
47         $message->fullmessage       = 'message body';
48         $message->fullmessageformat = FORMAT_MARKDOWN;
49         $message->fullmessagehtml   = '<p>message body</p>';
50         $message->smallmessage      = 'small message';
51         $message->notification      = 0;
53         // Check message is not sent.
54         $sink = $this->redirectEmails();
55         message_send($message);
56         $emails = $sink->get_messages();
57         $this->assertEmpty($emails);
59         // Check message is sent.
60         set_config($disableprovidersetting, 0, 'message');
61         $preferences = get_message_output_default_preferences();
62         $this->assertTrue($preferences->$disableprovidersetting == 0);
64         $sink = $this->redirectEmails();
65         message_send($message);
66         $emails = $sink->get_messages();
67         $email = reset($emails);
68         $this->assertEquals($email->subject, 'message subject 1');
69     }
70     public function test_message_get_providers_for_user() {
71         global $CFG, $DB;
73         $this->resetAfterTest();
75         $generator = $this->getDataGenerator();
77         // Create a course category and course.
78         $cat = $generator->create_category(array('parent' => 0));
79         $course = $generator->create_course(array('category' => $cat->id));
80         $quiz = $generator->create_module('quiz', array('course' => $course->id));
81         $user = $generator->create_user();
83         $coursecontext = context_course::instance($course->id);
84         $quizcontext = context_module::instance($quiz->cmid);
85         $frontpagecontext = context_course::instance(SITEID);
87         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
89         // The user is a student in a course, and has the capability for quiz
90         // confirmation emails in one quiz in that course.
91         role_assign($studentrole->id, $user->id, $coursecontext->id);
92         assign_capability('mod/quiz:emailconfirmsubmission', CAP_ALLOW, $studentrole->id, $quizcontext->id);
94         // Give this message type to the front page role.
95         assign_capability('mod/quiz:emailwarnoverdue', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpagecontext->id);
97         $providers = message_get_providers_for_user($user->id);
98         $this->assertTrue($this->message_type_present('mod_forum', 'posts', $providers));
99         $this->assertTrue($this->message_type_present('mod_quiz', 'confirmation', $providers));
100         $this->assertTrue($this->message_type_present('mod_quiz', 'attempt_overdue', $providers));
101         $this->assertFalse($this->message_type_present('mod_quiz', 'submission', $providers));
103         // A user is a student in a different course, they should not get confirmation.
104         $course2 = $generator->create_course(array('category' => $cat->id));
105         $user2 = $generator->create_user();
106         $coursecontext2 = context_course::instance($course2->id);
107         role_assign($studentrole->id, $user2->id, $coursecontext2->id);
108         accesslib_clear_all_caches_for_unit_testing();
109         $providers = message_get_providers_for_user($user2->id);
110         $this->assertTrue($this->message_type_present('mod_forum', 'posts', $providers));
111         $this->assertFalse($this->message_type_present('mod_quiz', 'confirmation', $providers));
113         // Now remove the frontpage role id, and attempt_overdue message should go away.
114         unset_config('defaultfrontpageroleid');
115         accesslib_clear_all_caches_for_unit_testing();
117         $providers = message_get_providers_for_user($user->id);
118         $this->assertTrue($this->message_type_present('mod_quiz', 'confirmation', $providers));
119         $this->assertFalse($this->message_type_present('mod_quiz', 'attempt_overdue', $providers));
120         $this->assertFalse($this->message_type_present('mod_quiz', 'submission', $providers));
121     }
123     public function test_message_get_providers_for_user_more() {
124         global $DB;
126         $this->resetAfterTest();
128         // Create a course.
129         $course = $this->getDataGenerator()->create_course();
130         $coursecontext = context_course::instance($course->id);
132         // It would probably be better to use a quiz instance as it has capability controlled messages
133         // however mod_quiz doesn't have a data generator.
134         // Instead we're going to use backup notifications and give and take away the capability at various levels.
135         $assign = $this->getDataGenerator()->create_module('assign', array('course'=>$course->id));
136         $modulecontext = context_module::instance($assign->cmid);
138         // Create and enrol a teacher.
139         $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST);
140         $teacher = $this->getDataGenerator()->create_user();
141         role_assign($teacherrole->id, $teacher->id, $coursecontext);
142         $enrolplugin = enrol_get_plugin('manual');
143         $enrolplugin->add_instance($course);
144         $enrolinstances = enrol_get_instances($course->id, false);
145         foreach ($enrolinstances as $enrolinstance) {
146             if ($enrolinstance->enrol === 'manual') {
147                 break;
148             }
149         }
150         $enrolplugin->enrol_user($enrolinstance, $teacher->id);
152         // Make the teacher the current user.
153         $this->setUser($teacher);
155         // Teacher shouldn't have the required capability so they shouldn't be able to see the backup message.
156         $this->assertFalse(has_capability('moodle/site:config', $modulecontext));
157         $providers = message_get_providers_for_user($teacher->id);
158         $this->assertFalse($this->message_type_present('moodle', 'backup', $providers));
160         // Give the user the required capability in an activity module.
161         // They should now be able to see the backup message.
162         assign_capability('moodle/site:config', CAP_ALLOW, $teacherrole->id, $modulecontext->id, true);
163         accesslib_clear_all_caches_for_unit_testing();
164         $modulecontext = context_module::instance($assign->cmid);
165         $this->assertTrue(has_capability('moodle/site:config', $modulecontext));
167         $providers = message_get_providers_for_user($teacher->id);
168         $this->assertTrue($this->message_type_present('moodle', 'backup', $providers));
170         // Prohibit the capability for the user at the course level.
171         // This overrules the CAP_ALLOW at the module level.
172         // They should not be able to see the backup message.
173         assign_capability('moodle/site:config', CAP_PROHIBIT, $teacherrole->id, $coursecontext->id, true);
174         accesslib_clear_all_caches_for_unit_testing();
175         $modulecontext = context_module::instance($assign->cmid);
176         $this->assertFalse(has_capability('moodle/site:config', $modulecontext));
178         $providers = message_get_providers_for_user($teacher->id);
179         // Actually, handling PROHIBITs would be too expensive. We do not
180         // care if users with PROHIBITs see a few more preferences than they should.
181         // $this->assertFalse($this->message_type_present('moodle', 'backup', $providers));
182     }
184     public function test_send_message_redirection() {
185         global $DB;
187         $this->resetAfterTest();
189         $user1 = $this->getDataGenerator()->create_user();
190         $user2 = $this->getDataGenerator()->create_user();
192         // Test basic message redirection.
193         $message = new \core\message\message();
194         $message->courseid = 1;
195         $message->component = 'moodle';
196         $message->name = 'instantmessage';
197         $message->userfrom = $user1;
198         $message->userto = $user2;
199         $message->subject = 'message subject 1';
200         $message->fullmessage = 'message body';
201         $message->fullmessageformat = FORMAT_MARKDOWN;
202         $message->fullmessagehtml = '<p>message body</p>';
203         $message->smallmessage = 'small message';
204         $message->notification = '0';
206         $sink = $this->redirectMessages();
207         $this->setCurrentTimeStart();
208         $messageid = message_send($message);
209         $savedmessages = $sink->get_messages();
210         $this->assertCount(1, $savedmessages);
211         $savedmessage = reset($savedmessages);
212         $this->assertEquals($messageid, $savedmessage->id);
213         $this->assertEquals($user1->id, $savedmessage->useridfrom);
214         $this->assertEquals($user2->id, $savedmessage->useridto);
215         $this->assertEquals($message->fullmessage, $savedmessage->fullmessage);
216         $this->assertEquals($message->fullmessageformat, $savedmessage->fullmessageformat);
217         $this->assertEquals($message->fullmessagehtml, $savedmessage->fullmessagehtml);
218         $this->assertEquals($message->smallmessage, $savedmessage->smallmessage);
219         $this->assertEquals($message->smallmessage, $savedmessage->smallmessage);
220         $this->assertEquals($message->notification, $savedmessage->notification);
221         $this->assertNull($savedmessage->contexturl);
222         $this->assertNull($savedmessage->contexturlname);
223         $this->assertTimeCurrent($savedmessage->timecreated);
224         $record = $DB->get_record('message_read', array('id' => $savedmessage->id), '*', MUST_EXIST);
225         $this->assertEquals($record, $savedmessage);
226         $sink->clear();
227         $this->assertFalse($DB->record_exists('message', array()));
228         $DB->delete_records('message_read', array());
230         $message = new \core\message\message();
231         $message->courseid = 1;
232         $message->component = 'moodle';
233         $message->name = 'instantmessage';
234         $message->userfrom = $user1->id;
235         $message->userto = $user2->id;
236         $message->subject = 'message subject 1';
237         $message->fullmessage = 'message body';
238         $message->fullmessageformat = FORMAT_MARKDOWN;
239         $message->fullmessagehtml = '<p>message body</p>';
240         $message->smallmessage = 'small message';
241         $message->notification = '0';
242         $message->contexturl = new moodle_url('/');
243         $message->contexturlname = 'front';
244         $sink = $this->redirectMessages();
245         $messageid = message_send($message);
246         $savedmessages = $sink->get_messages();
247         $this->assertCount(1, $savedmessages);
248         $savedmessage = reset($savedmessages);
249         $this->assertEquals($messageid, $savedmessage->id);
250         $this->assertEquals($user1->id, $savedmessage->useridfrom);
251         $this->assertEquals($user2->id, $savedmessage->useridto);
252         $this->assertEquals($message->fullmessage, $savedmessage->fullmessage);
253         $this->assertEquals($message->fullmessageformat, $savedmessage->fullmessageformat);
254         $this->assertEquals($message->fullmessagehtml, $savedmessage->fullmessagehtml);
255         $this->assertEquals($message->smallmessage, $savedmessage->smallmessage);
256         $this->assertEquals($message->smallmessage, $savedmessage->smallmessage);
257         $this->assertEquals($message->notification, $savedmessage->notification);
258         $this->assertEquals($message->contexturl->out(), $savedmessage->contexturl);
259         $this->assertEquals($message->contexturlname, $savedmessage->contexturlname);
260         $this->assertTimeCurrent($savedmessage->timecreated);
261         $record = $DB->get_record('message_read', array('id' => $savedmessage->id), '*', MUST_EXIST);
262         $this->assertEquals($record, $savedmessage);
263         $sink->clear();
264         $this->assertFalse($DB->record_exists('message', array()));
265         $DB->delete_records('message_read', array());
267         // Test phpunit problem detection.
269         $message = new \core\message\message();
270         $message->courseid = 1;
271         $message->component = 'xxxxx';
272         $message->name = 'instantmessage';
273         $message->userfrom = $user1;
274         $message->userto = $user2;
275         $message->subject = 'message subject 1';
276         $message->fullmessage = 'message body';
277         $message->fullmessageformat = FORMAT_MARKDOWN;
278         $message->fullmessagehtml = '<p>message body</p>';
279         $message->smallmessage = 'small message';
280         $message->notification = '0';
282         $sink = $this->redirectMessages();
283         try {
284             message_send($message);
285         } catch (moodle_exception $e) {
286             $this->assertInstanceOf('coding_exception', $e);
287         }
288         $this->assertCount(0, $sink->get_messages());
290         $message->component = 'moodle';
291         $message->name = 'xxx';
292         $sink = $this->redirectMessages();
293         try {
294             message_send($message);
295         } catch (moodle_exception $e) {
296             $this->assertInstanceOf('coding_exception', $e);
297         }
298         $this->assertCount(0, $sink->get_messages());
299         $sink->close();
300         $this->assertFalse($DB->record_exists('message', array()));
301         $this->assertFalse($DB->record_exists('message_read', array()));
303         // Invalid users.
305         $message = new \core\message\message();
306         $message->courseid = 1;
307         $message->component = 'moodle';
308         $message->name = 'instantmessage';
309         $message->userfrom = $user1;
310         $message->userto = -1;
311         $message->subject = 'message subject 1';
312         $message->fullmessage = 'message body';
313         $message->fullmessageformat = FORMAT_MARKDOWN;
314         $message->fullmessagehtml = '<p>message body</p>';
315         $message->smallmessage = 'small message';
316         $message->notification = '0';
318         $messageid = message_send($message);
319         $this->assertFalse($messageid);
320         $this->assertDebuggingCalled('Attempt to send msg to unknown user');
322         $message = new \core\message\message();
323         $message->courseid = 1;
324         $message->component = 'moodle';
325         $message->name = 'instantmessage';
326         $message->userfrom = -1;
327         $message->userto = $user2;
328         $message->subject = 'message subject 1';
329         $message->fullmessage = 'message body';
330         $message->fullmessageformat = FORMAT_MARKDOWN;
331         $message->fullmessagehtml = '<p>message body</p>';
332         $message->smallmessage = 'small message';
333         $message->notification = '0';
335         $messageid = message_send($message);
336         $this->assertFalse($messageid);
337         $this->assertDebuggingCalled('Attempt to send msg from unknown user');
339         $message = new \core\message\message();
340         $message->courseid = 1;
341         $message->component = 'moodle';
342         $message->name = 'instantmessage';
343         $message->userfrom = $user1;
344         $message->userto = core_user::NOREPLY_USER;
345         $message->subject = 'message subject 1';
346         $message->fullmessage = 'message body';
347         $message->fullmessageformat = FORMAT_MARKDOWN;
348         $message->fullmessagehtml = '<p>message body</p>';
349         $message->smallmessage = 'small message';
350         $message->notification = '0';
352         $messageid = message_send($message);
353         $this->assertFalse($messageid);
354         $this->assertDebuggingCalled('Attempt to send msg to internal (noreply) user');
356         // Some debugging hints for devs.
358         unset($user2->emailstop);
359         $message = new \core\message\message();
360         $message->courseid = 1;
361         $message->component = 'moodle';
362         $message->name = 'instantmessage';
363         $message->userfrom = $user1;
364         $message->userto = $user2;
365         $message->subject = 'message subject 1';
366         $message->fullmessage = 'message body';
367         $message->fullmessageformat = FORMAT_MARKDOWN;
368         $message->fullmessagehtml = '<p>message body</p>';
369         $message->smallmessage = 'small message';
370         $message->notification = '0';
372         $sink = $this->redirectMessages();
373         $messageid = message_send($message);
374         $savedmessages = $sink->get_messages();
375         $this->assertCount(1, $savedmessages);
376         $savedmessage = reset($savedmessages);
377         $this->assertEquals($messageid, $savedmessage->id);
378         $this->assertEquals($user1->id, $savedmessage->useridfrom);
379         $this->assertEquals($user2->id, $savedmessage->useridto);
380         $this->assertDebuggingCalled('Necessary properties missing in userto object, fetching full record');
381         $sink->clear();
382         $user2->emailstop = '0';
383     }
385     public function test_send_message() {
386         global $DB, $CFG;
387         $this->preventResetByRollback();
388         $this->resetAfterTest();
390         $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
391         $user2 = $this->getDataGenerator()->create_user();
392         set_config('allowedemaildomains', 'example.com');
394         // Test basic email redirection.
395         $this->assertFileExists("$CFG->dirroot/message/output/email/version.php");
396         $this->assertFileExists("$CFG->dirroot/message/output/popup/version.php");
398         $DB->set_field_select('message_processors', 'enabled', 0, "name <> 'email' AND name <> 'popup'");
399         get_message_processors(true, true);
401         $eventsink = $this->redirectEvents();
403         // Will always use the pop-up processor.
404         set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'none', $user2);
406         $message = new \core\message\message();
407         $message->courseid          = 1;
408         $message->component         = 'moodle';
409         $message->name              = 'instantmessage';
410         $message->userfrom          = $user1;
411         $message->userto            = $user2;
412         $message->subject           = 'message subject 1';
413         $message->fullmessage       = 'message body';
414         $message->fullmessageformat = FORMAT_MARKDOWN;
415         $message->fullmessagehtml   = '<p>message body</p>';
416         $message->smallmessage      = 'small message';
417         $message->notification      = '0';
419         $sink = $this->redirectEmails();
420         $messageid = message_send($message);
421         $emails = $sink->get_messages();
422         $this->assertCount(0, $emails);
423         $savedmessage = $DB->get_record('message', array('id' => $messageid), '*', MUST_EXIST);
424         $sink->clear();
425         $this->assertFalse($DB->record_exists('message_read', array()));
426         $DB->delete_records('message', array());
427         $events = $eventsink->get_events();
428         $this->assertCount(1, $events);
429         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
430         $eventsink->clear();
432         $CFG->messaging = 0;
434         $message = new \core\message\message();
435         $message->courseid          = 1;
436         $message->component         = 'moodle';
437         $message->name              = 'instantmessage';
438         $message->userfrom          = $user1;
439         $message->userto            = $user2;
440         $message->subject           = 'message subject 1';
441         $message->fullmessage       = 'message body';
442         $message->fullmessageformat = FORMAT_MARKDOWN;
443         $message->fullmessagehtml   = '<p>message body</p>';
444         $message->smallmessage      = 'small message';
445         $message->notification      = '0';
447         $messageid = message_send($message);
448         $emails = $sink->get_messages();
449         $this->assertCount(0, $emails);
450         $savedmessage = $DB->get_record('message_read', array('id' => $messageid), '*', MUST_EXIST);
451         $sink->clear();
452         $this->assertFalse($DB->record_exists('message', array()));
453         $DB->delete_records('message_read', array());
454         $events = $eventsink->get_events();
455         $this->assertCount(2, $events);
456         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
457         $this->assertInstanceOf('\core\event\message_viewed', $events[1]);
458         $eventsink->clear();
460         $CFG->messaging = 1;
462         $message = new \core\message\message();
463         $message->courseid          = 1;
464         $message->component         = 'moodle';
465         $message->name              = 'instantmessage';
466         $message->userfrom          = $user1;
467         $message->userto            = $user2;
468         $message->subject           = 'message subject 1';
469         $message->fullmessage       = 'message body';
470         $message->fullmessageformat = FORMAT_MARKDOWN;
471         $message->fullmessagehtml   = '<p>message body</p>';
472         $message->smallmessage      = 'small message';
473         $message->notification      = '1';
475         $messageid = message_send($message);
476         $emails = $sink->get_messages();
477         $this->assertCount(0, $emails);
478         $savedmessage = $DB->get_record('message_read', array('id' => $messageid), '*', MUST_EXIST);
479         $sink->clear();
480         $this->assertFalse($DB->record_exists('message', array()));
481         $DB->delete_records('message_read', array());
482         $events = $eventsink->get_events();
483         $this->assertCount(2, $events);
484         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
485         $this->assertInstanceOf('\core\event\message_viewed', $events[1]);
486         $eventsink->clear();
488         // Will always use the pop-up processor.
489         set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'email', $user2);
491         $message = new \core\message\message();
492         $message->courseid          = 1;
493         $message->component         = 'moodle';
494         $message->name              = 'instantmessage';
495         $message->userfrom          = $user1;
496         $message->userto            = $user2;
497         $message->subject           = 'message subject 1';
498         $message->fullmessage       = 'message body';
499         $message->fullmessageformat = FORMAT_MARKDOWN;
500         $message->fullmessagehtml   = '<p>message body</p>';
501         $message->smallmessage      = 'small message';
502         $message->notification      = '0';
504         $user2->emailstop = '1';
506         $sink = $this->redirectEmails();
507         $messageid = message_send($message);
508         $emails = $sink->get_messages();
509         $this->assertCount(0, $emails);
510         $savedmessage = $DB->get_record('message', array('id' => $messageid), '*', MUST_EXIST);
511         $sink->clear();
512         $this->assertFalse($DB->record_exists('message_read', array()));
513         $DB->delete_records('message', array());
514         $events = $eventsink->get_events();
515         $this->assertCount(1, $events);
516         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
517         $eventsink->clear();
518         $user2->emailstop = '0';
520         // Will always use the pop-up processor.
521         set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'email', $user2);
523         $message = new \core\message\message();
524         $message->courseid          = 1;
525         $message->component         = 'moodle';
526         $message->name              = 'instantmessage';
527         $message->userfrom          = $user1;
528         $message->userto            = $user2;
529         $message->subject           = 'message subject 1';
530         $message->fullmessage       = 'message body';
531         $message->fullmessageformat = FORMAT_MARKDOWN;
532         $message->fullmessagehtml   = '<p>message body</p>';
533         $message->smallmessage      = 'small message';
534         $message->notification      = '0';
536         $messageid = message_send($message);
537         $emails = $sink->get_messages();
538         $this->assertCount(1, $emails);
539         $email = reset($emails);
540         $savedmessage = $DB->get_record('message', array('id' => $messageid), '*', MUST_EXIST);
541         $this->assertSame($user1->email, $email->from);
542         $this->assertSame($user2->email, $email->to);
543         $this->assertSame($message->subject, $email->subject);
544         $this->assertNotEmpty($email->header);
545         $this->assertNotEmpty($email->body);
546         $sink->clear();
547         $this->assertFalse($DB->record_exists('message_read', array()));
548         $DB->delete_records('message_read', array());
549         $events = $eventsink->get_events();
550         $this->assertCount(1, $events);
551         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
552         $eventsink->clear();
554         set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'email,popup', $user2);
556         $message = new \core\message\message();
557         $message->courseid          = 1;
558         $message->component         = 'moodle';
559         $message->name              = 'instantmessage';
560         $message->userfrom          = $user1;
561         $message->userto            = $user2;
562         $message->subject           = 'message subject 1';
563         $message->fullmessage       = 'message body';
564         $message->fullmessageformat = FORMAT_MARKDOWN;
565         $message->fullmessagehtml   = '<p>message body</p>';
566         $message->smallmessage      = 'small message';
567         $message->notification      = '0';
569         $messageid = message_send($message);
570         $emails = $sink->get_messages();
571         $this->assertCount(1, $emails);
572         $email = reset($emails);
573         $savedmessage = $DB->get_record('message', array('id' => $messageid), '*', MUST_EXIST);
574         $working = $DB->get_record('message_working', array('unreadmessageid' => $messageid), '*', MUST_EXIST);
575         $this->assertSame($user1->email, $email->from);
576         $this->assertSame($user2->email, $email->to);
577         $this->assertSame($message->subject, $email->subject);
578         $this->assertNotEmpty($email->header);
579         $this->assertNotEmpty($email->body);
580         $sink->clear();
581         $this->assertFalse($DB->record_exists('message_read', array()));
582         $DB->delete_records('message', array());
583         $events = $eventsink->get_events();
584         $this->assertCount(1, $events);
585         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
586         $eventsink->clear();
588         set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'popup', $user2);
590         $message = new \core\message\message();
591         $message->courseid          = 1;
592         $message->component         = 'moodle';
593         $message->name              = 'instantmessage';
594         $message->userfrom          = $user1;
595         $message->userto            = $user2;
596         $message->subject           = 'message subject 1';
597         $message->fullmessage       = 'message body';
598         $message->fullmessageformat = FORMAT_MARKDOWN;
599         $message->fullmessagehtml   = '<p>message body</p>';
600         $message->smallmessage      = 'small message';
601         $message->notification      = '0';
603         $messageid = message_send($message);
604         $emails = $sink->get_messages();
605         $this->assertCount(0, $emails);
606         $savedmessage = $DB->get_record('message', array('id' => $messageid), '*', MUST_EXIST);
607         $working = $DB->get_record('message_working', array('unreadmessageid' => $messageid), '*', MUST_EXIST);
608         $sink->clear();
609         $this->assertFalse($DB->record_exists('message_read', array()));
610         $DB->delete_records('message', array());
611         $events = $eventsink->get_events();
612         $this->assertCount(1, $events);
613         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
614         $eventsink->clear();
616         $this->assertFalse($DB->is_transaction_started());
617         $transaction = $DB->start_delegated_transaction();
618         if (!$DB->is_transaction_started()) {
619             $this->markTestSkipped('Databases that do not support transactions should not be used at all!');
620         }
621         $transaction->allow_commit();
623         // Will always use the pop-up processor.
624         set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'none', $user2);
626         $message = new \core\message\message();
627         $message->courseid          = 1;
628         $message->component         = 'moodle';
629         $message->name              = 'instantmessage';
630         $message->userfrom          = $user1;
631         $message->userto            = $user2;
632         $message->subject           = 'message subject 1';
633         $message->fullmessage       = 'message body';
634         $message->fullmessageformat = FORMAT_MARKDOWN;
635         $message->fullmessagehtml   = '<p>message body</p>';
636         $message->smallmessage      = 'small message';
637         $message->notification      = '0';
639         $transaction = $DB->start_delegated_transaction();
640         $sink = $this->redirectEmails();
641         $messageid = message_send($message);
642         $emails = $sink->get_messages();
643         $this->assertCount(0, $emails);
644         $savedmessage = $DB->get_record('message', array('id' => $messageid), '*', MUST_EXIST);
645         $sink->clear();
646         $this->assertFalse($DB->record_exists('message_read', array()));
647         $DB->delete_records('message', array());
648         $events = $eventsink->get_events();
649         $this->assertCount(0, $events);
650         $eventsink->clear();
651         $transaction->allow_commit();
652         $events = $eventsink->get_events();
653         $this->assertCount(1, $events);
654         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
656         // Will always use the pop-up processor.
657         set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'email', $user2);
659         $message = new \core\message\message();
660         $message->courseid          = 1;
661         $message->component         = 'moodle';
662         $message->name              = 'instantmessage';
663         $message->userfrom          = $user1;
664         $message->userto            = $user2;
665         $message->subject           = 'message subject 1';
666         $message->fullmessage       = 'message body';
667         $message->fullmessageformat = FORMAT_MARKDOWN;
668         $message->fullmessagehtml   = '<p>message body</p>';
669         $message->smallmessage      = 'small message';
670         $message->notification      = '0';
672         $transaction = $DB->start_delegated_transaction();
673         $sink = $this->redirectEmails();
674         $messageid = message_send($message);
675         $emails = $sink->get_messages();
676         $this->assertCount(0, $emails);
677         $savedmessage = $DB->get_record('message', array('id' => $messageid), '*', MUST_EXIST);
678         $sink->clear();
679         $this->assertFalse($DB->record_exists('message_read', array()));
680         $events = $eventsink->get_events();
681         $this->assertCount(1, $events);
682         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
683         $transaction->allow_commit();
684         $events = $eventsink->get_events();
685         $this->assertCount(2, $events);
686         $this->assertInstanceOf('\core\event\message_sent', $events[1]);
687         $eventsink->clear();
689         $transaction = $DB->start_delegated_transaction();
690         message_send($message);
691         message_send($message);
692         $this->assertCount(3, $DB->get_records('message'));
693         $this->assertFalse($DB->record_exists('message_read', array()));
694         $events = $eventsink->get_events();
695         $this->assertCount(0, $events);
696         $transaction->allow_commit();
697         $events = $eventsink->get_events();
698         $this->assertCount(2, $events);
699         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
700         $this->assertInstanceOf('\core\event\message_sent', $events[1]);
701         $eventsink->clear();
702         $DB->delete_records('message', array());
703         $DB->delete_records('message_read', array());
705         $transaction = $DB->start_delegated_transaction();
706         message_send($message);
707         message_send($message);
708         $this->assertCount(2, $DB->get_records('message'));
709         $this->assertCount(0, $DB->get_records('message_read'));
710         $events = $eventsink->get_events();
711         $this->assertCount(0, $events);
712         try {
713             $transaction->rollback(new Exception('ignore'));
714         } catch (Exception $e) {
715             $this->assertSame('ignore', $e->getMessage());
716         }
717         $events = $eventsink->get_events();
718         $this->assertCount(0, $events);
719         $this->assertCount(0, $DB->get_records('message'));
720         $this->assertCount(0, $DB->get_records('message_read'));
721         message_send($message);
722         $this->assertCount(1, $DB->get_records('message'));
723         $this->assertCount(0, $DB->get_records('message_read'));
724         $events = $eventsink->get_events();
725         $this->assertCount(1, $events);
726         $this->assertInstanceOf('\core\event\message_sent', $events[0]);
727         $sink->clear();
728         $DB->delete_records('message_read', array());
729     }
731     public function test_rollback() {
732         global $DB;
734         $this->resetAfterTest();
735         $this->preventResetByRollback();
737         $user1 = $this->getDataGenerator()->create_user();
738         $user2 = $this->getDataGenerator()->create_user();
740         $message = new \core\message\message();
741         $message->courseid          = 1;
742         $message->component         = 'moodle';
743         $message->name              = 'instantmessage';
744         $message->userfrom          = $user1;
745         $message->userto            = $user2;
746         $message->subject           = 'message subject 1';
747         $message->fullmessage       = 'message body';
748         $message->fullmessageformat = FORMAT_MARKDOWN;
749         $message->fullmessagehtml   = '<p>message body</p>';
750         $message->smallmessage      = 'small message';
751         $message->notification      = '0';
753         $mailsink = $this->redirectEmails();
755         // Sending outside of a transaction is fine.
756         message_send($message);
757         $this->assertEquals(1, $mailsink->count());
759         $transaction1 = $DB->start_delegated_transaction();
761         $mailsink->clear();
762         message_send($message);
763         $this->assertEquals(0, $mailsink->count());
765         $transaction2 = $DB->start_delegated_transaction();
767         $mailsink->clear();
768         message_send($message);
769         $this->assertEquals(0, $mailsink->count());
771         try {
772             $transaction2->rollback(new Exception('x'));
773             $this->fail('Expecting exception');
774         } catch (Exception $e) {}
775         $this->assertDebuggingNotCalled();
776         $this->assertEquals(0, $mailsink->count());
778         $this->assertTrue($DB->is_transaction_started());
780         try {
781             $transaction1->rollback(new Exception('x'));
782             $this->fail('Expecting exception');
783         } catch (Exception $e) {}
784         $this->assertDebuggingNotCalled();
785         $this->assertEquals(0, $mailsink->count());
787         $this->assertFalse($DB->is_transaction_started());
789         message_send($message);
790         $this->assertEquals(1, $mailsink->count());
791     }
793     public function test_forced_rollback() {
794         global $DB;
796         $this->resetAfterTest();
797         $this->preventResetByRollback();
798         set_config('noemailever', 1);
800         $user1 = $this->getDataGenerator()->create_user();
801         $user2 = $this->getDataGenerator()->create_user();
803         $message = new \core\message\message();
804         $message->courseid          = 1;
805         $message->component         = 'moodle';
806         $message->name              = 'instantmessage';
807         $message->userfrom          = $user1;
808         $message->userto            = $user2;
809         $message->subject           = 'message subject 1';
810         $message->fullmessage       = 'message body';
811         $message->fullmessageformat = FORMAT_MARKDOWN;
812         $message->fullmessagehtml   = '<p>message body</p>';
813         $message->smallmessage      = 'small message';
814         $message->notification      = '0';
816         message_send($message);
817         $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
819         $transaction1 = $DB->start_delegated_transaction();
821         message_send($message);
822         $this->assertDebuggingNotCalled();
824         $transaction2 = $DB->start_delegated_transaction();
826         message_send($message);
827         $this->assertDebuggingNotCalled();
829         $DB->force_transaction_rollback();
830         $this->assertFalse($DB->is_transaction_started());
831         $this->assertDebuggingNotCalled();
833         message_send($message);
834         $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
835     }
837     public function test_message_attachment_send() {
838         global $CFG;
839         $this->preventResetByRollback();
840         $this->resetAfterTest();
842         // Set config setting to allow attachments.
843         $CFG->allowattachments = true;
844         unset_config('noemailever');
846         $user = $this->getDataGenerator()->create_user();
847         $context = context_user::instance($user->id);
849         // Create a test file.
850         $fs = get_file_storage();
851         $filerecord = array(
852                 'contextid' => $context->id,
853                 'component' => 'core',
854                 'filearea'  => 'unittest',
855                 'itemid'    => 99999,
856                 'filepath'  => '/',
857                 'filename'  => 'emailtest.txt'
858         );
859         $file = $fs->create_file_from_string($filerecord, 'Test content');
861         $message = new \core\message\message();
862         $message->courseid          = 1;
863         $message->component         = 'moodle';
864         $message->name              = 'instantmessage';
865         $message->userfrom          = get_admin();
866         $message->userto            = $user;
867         $message->subject           = 'message subject 1';
868         $message->fullmessage       = 'message body';
869         $message->fullmessageformat = FORMAT_MARKDOWN;
870         $message->fullmessagehtml   = '<p>message body</p>';
871         $message->smallmessage      = 'small message';
872         $message->attachment        = $file;
873         $message->attachname        = 'emailtest.txt';
874         $message->notification      = 0;
876         // Make sure we are redirecting emails.
877         $sink = $this->redirectEmails();
878         message_send($message);
880         // Get the email that we just sent.
881         $emails = $sink->get_messages();
882         $email = reset($emails);
883         $this->assertTrue(strpos($email->body, 'Content-Disposition: attachment;') !== false);
884         $this->assertTrue(strpos($email->body, 'emailtest.txt') !== false);
886         // Check if the stored file still exists after remove the temporary attachment.
887         $storedfileexists = $fs->file_exists($filerecord['contextid'], $filerecord['component'], $filerecord['filearea'],
888                                              $filerecord['itemid'], $filerecord['filepath'], $filerecord['filename']);
889         $this->assertTrue($storedfileexists);
890     }
892     /**
893      * Is a particular message type in the list of message types.
894      * @param string $component
895      * @param string $name a message name.
896      * @param array $providers as returned by message_get_providers_for_user.
897      * @return bool whether the message type is present.
898      */
899     protected function message_type_present($component, $name, $providers) {
900         foreach ($providers as $provider) {
901             if ($provider->component == $component && $provider->name == $name) {
902                 return true;
903             }
904         }
905         return false;
906     }