Pull merge.
[yaffs-website] / web / core / modules / system / tests / src / Functional / Mail / MailTest.php
1 <?php
2
3 namespace Drupal\Tests\system\Functional\Mail;
4
5 use Drupal\Component\Utility\Random;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Mail\MailFormatHelper;
8 use Drupal\Core\Mail\Plugin\Mail\TestMailCollector;
9 use Drupal\Core\Render\Markup;
10 use Drupal\Core\Url;
11 use Drupal\file\Entity\File;
12 use Drupal\Tests\BrowserTestBase;
13 use Drupal\system_mail_failure_test\Plugin\Mail\TestPhpMailFailure;
14
15 /**
16  * Performs tests on the pluggable mailing framework.
17  *
18  * @group Mail
19  */
20 class MailTest extends BrowserTestBase {
21
22   /**
23    * Modules to enable.
24    *
25    * @var array
26    */
27   public static $modules = ['simpletest', 'system_mail_failure_test', 'mail_html_test', 'file', 'image'];
28
29   /**
30    * Assert that the pluggable mail system is functional.
31    */
32   public function testPluggableFramework() {
33     // Switch mail backends.
34     $this->config('system.mail')->set('interface.default', 'test_php_mail_failure')->save();
35
36     // Get the default MailInterface class instance.
37     $mail_backend = \Drupal::service('plugin.manager.mail')->getInstance(['module' => 'default', 'key' => 'default']);
38
39     // Assert whether the default mail backend is an instance of the expected
40     // class.
41     $this->assertTrue($mail_backend instanceof TestPhpMailFailure, 'Default mail interface can be swapped.');
42
43     // Add a module-specific mail backend.
44     $this->config('system.mail')->set('interface.mymodule_testkey', 'test_mail_collector')->save();
45
46     // Get the added MailInterface class instance.
47     $mail_backend = \Drupal::service('plugin.manager.mail')->getInstance(['module' => 'mymodule', 'key' => 'testkey']);
48
49     // Assert whether the added mail backend is an instance of the expected
50     // class.
51     $this->assertTrue($mail_backend instanceof TestMailCollector, 'Additional mail interfaces can be added.');
52   }
53
54   /**
55    * Test that message sending may be canceled.
56    *
57    * @see simpletest_mail_alter()
58    */
59   public function testCancelMessage() {
60     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
61
62     // Use the state system collector mail backend.
63     $this->config('system.mail')->set('interface.default', 'test_mail_collector')->save();
64     // Reset the state variable that holds sent messages.
65     \Drupal::state()->set('system.test_mail_collector', []);
66
67     // Send a test message that simpletest_mail_alter should cancel.
68     \Drupal::service('plugin.manager.mail')->mail('simpletest', 'cancel_test', 'cancel@example.com', $language_interface->getId());
69     // Retrieve sent message.
70     $captured_emails = \Drupal::state()->get('system.test_mail_collector');
71     $sent_message = end($captured_emails);
72
73     // Assert that the message was not actually sent.
74     $this->assertFalse($sent_message, 'Message was canceled.');
75   }
76
77   /**
78    * Checks the From: and Reply-to: headers.
79    */
80   public function testFromAndReplyToHeader() {
81     $language = \Drupal::languageManager()->getCurrentLanguage();
82
83     // Use the state system collector mail backend.
84     $this->config('system.mail')->set('interface.default', 'test_mail_collector')->save();
85     // Reset the state variable that holds sent messages.
86     \Drupal::state()->set('system.test_mail_collector', []);
87     // Send an email with a reply-to address specified.
88     $from_email = 'Drupal <simpletest@example.com>';
89     $reply_email = 'someone_else@example.com';
90     \Drupal::service('plugin.manager.mail')->mail('simpletest', 'from_test', 'from_test@example.com', $language, [], $reply_email);
91     // Test that the reply-to email is just the email and not the site name
92     // and default sender email.
93     $captured_emails = \Drupal::state()->get('system.test_mail_collector');
94     $sent_message = end($captured_emails);
95     $this->assertEqual($from_email, $sent_message['headers']['From'], 'Message is sent from the site email account.');
96     $this->assertEqual($reply_email, $sent_message['headers']['Reply-to'], 'Message reply-to headers are set.');
97     $this->assertFalse(isset($sent_message['headers']['Errors-To']), 'Errors-to header must not be set, it is deprecated.');
98
99     // Test that long site names containing characters that need MIME encoding
100     // works as expected.
101     $this->config('system.site')->set('name', 'Drépal this is a very long test sentence to test what happens with very long site names')->save();
102     // Send an email and check that the From-header contains the site name.
103     \Drupal::service('plugin.manager.mail')->mail('simpletest', 'from_test', 'from_test@example.com', $language);
104     $captured_emails = \Drupal::state()->get('system.test_mail_collector');
105     $sent_message = end($captured_emails);
106     $this->assertEquals('=?UTF-8?B?RHLDqXBhbCB0aGlzIGlzIGEgdmVyeSBsb25nIHRlc3Qgc2VudGVuY2UgdG8gdGU=?= <simpletest@example.com>', $sent_message['headers']['From'], 'From header is correctly encoded.');
107     $this->assertEquals('Drépal this is a very long test sentence to te <simpletest@example.com>', Unicode::mimeHeaderDecode($sent_message['headers']['From']), 'From header is correctly encoded.');
108     $this->assertFalse(isset($sent_message['headers']['Reply-to']), 'Message reply-to is not set if not specified.');
109     $this->assertFalse(isset($sent_message['headers']['Errors-To']), 'Errors-to header must not be set, it is deprecated.');
110
111     // Test RFC-2822 rules are respected for 'display-name' component of
112     // 'From:' header. Specials characters are not allowed, so randomly add one
113     // of them to the site name and check the string is wrapped in quotes. Also
114     // hardcode some double-quotes and backslash to validate these are escaped
115     // properly too.
116     $specials = '()<>[]:;@\,."';
117     $site_name = 'Drupal' . $specials[rand(0, strlen($specials) - 1)] . ' "si\te"';
118     $this->config('system.site')->set('name', $site_name)->save();
119     // Send an email and check that the From-header contains the site name
120     // within double-quotes. Also make sure double-quotes and "\" are escaped.
121     \Drupal::service('plugin.manager.mail')->mail('simpletest', 'from_test', 'from_test@example.com', $language);
122     $captured_emails = \Drupal::state()->get('system.test_mail_collector');
123     $sent_message = end($captured_emails);
124     $escaped_site_name = str_replace(['\\', '"'], ['\\\\', '\\"'], $site_name);
125     $this->assertEquals('"' . $escaped_site_name . '" <simpletest@example.com>', $sent_message['headers']['From'], 'From header is correctly quoted.');
126
127     // Make sure display-name is not quoted nor escaped if part on an encoding.
128     $site_name = 'Drépal, "si\te"';
129     $this->config('system.site')->set('name', $site_name)->save();
130     // Send an email and check that the From-header contains the site name.
131     \Drupal::service('plugin.manager.mail')->mail('simpletest', 'from_test', 'from_test@example.com', $language);
132     $captured_emails = \Drupal::state()->get('system.test_mail_collector');
133     $sent_message = end($captured_emails);
134     $this->assertEquals('=?UTF-8?B?RHLDqXBhbCwgInNpXHRlIg==?= <simpletest@example.com>', $sent_message['headers']['From'], 'From header is correctly encoded.');
135     $this->assertEquals($site_name . ' <simpletest@example.com>', Unicode::mimeHeaderDecode($sent_message['headers']['From']), 'From header is correctly encoded.');
136   }
137
138   /**
139    * Checks that relative paths in mails are converted into absolute URLs.
140    */
141   public function testConvertRelativeUrlsIntoAbsolute() {
142     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
143
144     // Use the HTML compatible state system collector mail backend.
145     $this->config('system.mail')->set('interface.default', 'test_html_mail_collector')->save();
146
147     // Fetch the hostname and port for matching against.
148     $http_host = \Drupal::request()->getSchemeAndHttpHost();
149
150     // Random generator.
151     $random = new Random();
152
153     // One random tag name.
154     $tag_name = strtolower($random->name(8, TRUE));
155
156     // Test root relative urls.
157     foreach (['href', 'src'] as $attribute) {
158       // Reset the state variable that holds sent messages.
159       \Drupal::state()->set('system.test_mail_collector', []);
160
161       $html = "<$tag_name $attribute=\"/root-relative\">root relative url in mail test</$tag_name>";
162       $expected_html = "<$tag_name $attribute=\"{$http_host}/root-relative\">root relative url in mail test</$tag_name>";
163
164       // Prepare render array.
165       $render = ['#markup' => Markup::create($html)];
166
167       // Send a test message that simpletest_mail_alter should cancel.
168       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
169       // Retrieve sent message.
170       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
171       $sent_message = end($captured_emails);
172
173       // Wrap the expected HTML and assert.
174       $expected_html = MailFormatHelper::wrapMail($expected_html);
175       $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$attribute} is properly converted for mails.");
176     }
177
178     // Test protocol relative urls.
179     foreach (['href', 'src'] as $attribute) {
180       // Reset the state variable that holds sent messages.
181       \Drupal::state()->set('system.test_mail_collector', []);
182
183       $html = "<$tag_name $attribute=\"//example.com/protocol-relative\">protocol relative url in mail test</$tag_name>";
184       $expected_html = "<$tag_name $attribute=\"//example.com/protocol-relative\">protocol relative url in mail test</$tag_name>";
185
186       // Prepare render array.
187       $render = ['#markup' => Markup::create($html)];
188
189       // Send a test message that simpletest_mail_alter should cancel.
190       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
191       // Retrieve sent message.
192       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
193       $sent_message = end($captured_emails);
194
195       // Wrap the expected HTML and assert.
196       $expected_html = MailFormatHelper::wrapMail($expected_html);
197       $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$attribute} is properly converted for mails.");
198     }
199
200     // Test absolute urls.
201     foreach (['href', 'src'] as $attribute) {
202       // Reset the state variable that holds sent messages.
203       \Drupal::state()->set('system.test_mail_collector', []);
204
205       $html = "<$tag_name $attribute=\"http://example.com/absolute\">absolute url in mail test</$tag_name>";
206       $expected_html = "<$tag_name $attribute=\"http://example.com/absolute\">absolute url in mail test</$tag_name>";
207
208       // Prepare render array.
209       $render = ['#markup' => Markup::create($html)];
210
211       // Send a test message that simpletest_mail_alter should cancel.
212       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
213       // Retrieve sent message.
214       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
215       $sent_message = end($captured_emails);
216
217       // Wrap the expected HTML and assert.
218       $expected_html = MailFormatHelper::wrapMail($expected_html);
219       $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$attribute} is properly converted for mails.");
220     }
221   }
222
223   /**
224    * Checks that mails built from render arrays contain absolute paths.
225    *
226    * By default Drupal uses relative paths for images and links. When sending
227    * emails, absolute paths should be used instead.
228    */
229   public function testRenderedElementsUseAbsolutePaths() {
230     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
231
232     // Use the HTML compatible state system collector mail backend.
233     $this->config('system.mail')->set('interface.default', 'test_html_mail_collector')->save();
234
235     // Fetch the hostname and port for matching against.
236     $http_host = \Drupal::request()->getSchemeAndHttpHost();
237
238     // Random generator.
239     $random = new Random();
240     $image_name = $random->name();
241
242     // Create an image file.
243     $file = File::create(['uri' => "public://{$image_name}.png", 'filename' => "{$image_name}.png"]);
244     $file->save();
245
246     $base_path = base_path();
247
248     $path_pairs = [
249       'root relative' => [$file->getFileUri(), "{$http_host}{$base_path}{$this->publicFilesDirectory}/{$image_name}.png"],
250       'protocol relative' => ['//example.com/image.png', '//example.com/image.png'],
251       'absolute' => ['http://example.com/image.png', 'http://example.com/image.png'],
252     ];
253
254     // Test images.
255     foreach ($path_pairs as $test_type => $paths) {
256       list($input_path, $expected_path) = $paths;
257
258       // Reset the state variable that holds sent messages.
259       \Drupal::state()->set('system.test_mail_collector', []);
260
261       // Build the render array.
262       $render = [
263         '#theme' => 'image',
264         '#uri' => $input_path,
265       ];
266       $expected_html = "<img src=\"$expected_path\" alt=\"\" />";
267
268       // Send a test message that simpletest_mail_alter should cancel.
269       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
270       // Retrieve sent message.
271       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
272       $sent_message = end($captured_emails);
273
274       // Wrap the expected HTML and assert.
275       $expected_html = MailFormatHelper::wrapMail($expected_html);
276       $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$test_type} paths are converted properly.");
277     }
278
279     // Test links.
280     $path_pairs = [
281       'root relative' => [Url::fromUserInput('/path/to/something'), "{$http_host}{$base_path}path/to/something"],
282       'protocol relative' => [Url::fromUri('//example.com/image.png'), '//example.com/image.png'],
283       'absolute' => [Url::fromUri('http://example.com/image.png'), 'http://example.com/image.png'],
284     ];
285
286     foreach ($path_pairs as $paths) {
287       list($input_path, $expected_path) = $paths;
288
289       // Reset the state variable that holds sent messages.
290       \Drupal::state()->set('system.test_mail_collector', []);
291
292       // Build the render array.
293       $render = [
294         '#title' => 'Link',
295         '#type' => 'link',
296         '#url' => $input_path,
297       ];
298       $expected_html = "<a href=\"$expected_path\">Link</a>";
299
300       // Send a test message that simpletest_mail_alter should cancel.
301       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
302       // Retrieve sent message.
303       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
304       $sent_message = end($captured_emails);
305
306       // Wrap the expected HTML and assert.
307       $expected_html = MailFormatHelper::wrapMail($expected_html);
308       $this->assertSame($expected_html, $sent_message['body']);
309     }
310   }
311
312 }