Updated to Drupal 8.6.4, which is PHP 7.3 friendly. Also updated HTMLaw library....
[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
112   /**
113    * Checks that relative paths in mails are converted into absolute URLs.
114    */
115   public function testConvertRelativeUrlsIntoAbsolute() {
116     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
117
118     // Use the HTML compatible state system collector mail backend.
119     $this->config('system.mail')->set('interface.default', 'test_html_mail_collector')->save();
120
121     // Fetch the hostname and port for matching against.
122     $http_host = \Drupal::request()->getSchemeAndHttpHost();
123
124     // Random generator.
125     $random = new Random();
126
127     // One random tag name.
128     $tag_name = strtolower($random->name(8, TRUE));
129
130     // Test root relative urls.
131     foreach (['href', 'src'] as $attribute) {
132       // Reset the state variable that holds sent messages.
133       \Drupal::state()->set('system.test_mail_collector', []);
134
135       $html = "<$tag_name $attribute=\"/root-relative\">root relative url in mail test</$tag_name>";
136       $expected_html = "<$tag_name $attribute=\"{$http_host}/root-relative\">root relative url in mail test</$tag_name>";
137
138       // Prepare render array.
139       $render = ['#markup' => Markup::create($html)];
140
141       // Send a test message that simpletest_mail_alter should cancel.
142       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
143       // Retrieve sent message.
144       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
145       $sent_message = end($captured_emails);
146
147       // Wrap the expected HTML and assert.
148       $expected_html = MailFormatHelper::wrapMail($expected_html);
149       $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$attribute} is properly converted for mails.");
150     }
151
152     // Test protocol relative urls.
153     foreach (['href', 'src'] as $attribute) {
154       // Reset the state variable that holds sent messages.
155       \Drupal::state()->set('system.test_mail_collector', []);
156
157       $html = "<$tag_name $attribute=\"//example.com/protocol-relative\">protocol relative url in mail test</$tag_name>";
158       $expected_html = "<$tag_name $attribute=\"//example.com/protocol-relative\">protocol relative url in mail test</$tag_name>";
159
160       // Prepare render array.
161       $render = ['#markup' => Markup::create($html)];
162
163       // Send a test message that simpletest_mail_alter should cancel.
164       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
165       // Retrieve sent message.
166       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
167       $sent_message = end($captured_emails);
168
169       // Wrap the expected HTML and assert.
170       $expected_html = MailFormatHelper::wrapMail($expected_html);
171       $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$attribute} is properly converted for mails.");
172     }
173
174     // Test absolute urls.
175     foreach (['href', 'src'] as $attribute) {
176       // Reset the state variable that holds sent messages.
177       \Drupal::state()->set('system.test_mail_collector', []);
178
179       $html = "<$tag_name $attribute=\"http://example.com/absolute\">absolute url in mail test</$tag_name>";
180       $expected_html = "<$tag_name $attribute=\"http://example.com/absolute\">absolute url in mail test</$tag_name>";
181
182       // Prepare render array.
183       $render = ['#markup' => Markup::create($html)];
184
185       // Send a test message that simpletest_mail_alter should cancel.
186       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
187       // Retrieve sent message.
188       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
189       $sent_message = end($captured_emails);
190
191       // Wrap the expected HTML and assert.
192       $expected_html = MailFormatHelper::wrapMail($expected_html);
193       $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$attribute} is properly converted for mails.");
194     }
195   }
196
197   /**
198    * Checks that mails built from render arrays contain absolute paths.
199    *
200    * By default Drupal uses relative paths for images and links. When sending
201    * emails, absolute paths should be used instead.
202    */
203   public function testRenderedElementsUseAbsolutePaths() {
204     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
205
206     // Use the HTML compatible state system collector mail backend.
207     $this->config('system.mail')->set('interface.default', 'test_html_mail_collector')->save();
208
209     // Fetch the hostname and port for matching against.
210     $http_host = \Drupal::request()->getSchemeAndHttpHost();
211
212     // Random generator.
213     $random = new Random();
214     $image_name = $random->name();
215
216     // Create an image file.
217     $file = File::create(['uri' => "public://{$image_name}.png", 'filename' => "{$image_name}.png"]);
218     $file->save();
219
220     $base_path = base_path();
221
222     $path_pairs = [
223       'root relative' => [$file->getFileUri(), "{$http_host}{$base_path}{$this->publicFilesDirectory}/{$image_name}.png"],
224       'protocol relative' => ['//example.com/image.png', '//example.com/image.png'],
225       'absolute' => ['http://example.com/image.png', 'http://example.com/image.png'],
226     ];
227
228     // Test images.
229     foreach ($path_pairs as $test_type => $paths) {
230       list($input_path, $expected_path) = $paths;
231
232       // Reset the state variable that holds sent messages.
233       \Drupal::state()->set('system.test_mail_collector', []);
234
235       // Build the render array.
236       $render = [
237         '#theme' => 'image',
238         '#uri' => $input_path,
239       ];
240       $expected_html = "<img src=\"$expected_path\" alt=\"\" />";
241
242       // Send a test message that simpletest_mail_alter should cancel.
243       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
244       // Retrieve sent message.
245       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
246       $sent_message = end($captured_emails);
247
248       // Wrap the expected HTML and assert.
249       $expected_html = MailFormatHelper::wrapMail($expected_html);
250       $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$test_type} paths are converted properly.");
251     }
252
253     // Test links.
254     $path_pairs = [
255       'root relative' => [Url::fromUserInput('/path/to/something'), "{$http_host}{$base_path}path/to/something"],
256       'protocol relative' => [Url::fromUri('//example.com/image.png'), '//example.com/image.png'],
257       'absolute' => [Url::fromUri('http://example.com/image.png'), 'http://example.com/image.png'],
258     ];
259
260     foreach ($path_pairs as $paths) {
261       list($input_path, $expected_path) = $paths;
262
263       // Reset the state variable that holds sent messages.
264       \Drupal::state()->set('system.test_mail_collector', []);
265
266       // Build the render array.
267       $render = [
268         '#title' => 'Link',
269         '#type' => 'link',
270         '#url' => $input_path,
271       ];
272       $expected_html = "<a href=\"$expected_path\">Link</a>";
273
274       // Send a test message that simpletest_mail_alter should cancel.
275       \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
276       // Retrieve sent message.
277       $captured_emails = \Drupal::state()->get('system.test_mail_collector');
278       $sent_message = end($captured_emails);
279
280       // Wrap the expected HTML and assert.
281       $expected_html = MailFormatHelper::wrapMail($expected_html);
282       $this->assertSame($expected_html, $sent_message['body']);
283     }
284   }
285
286 }