3 namespace Drupal\Tests\contact\Functional;
5 use Drupal\contact\Entity\ContactForm;
6 use Drupal\Core\Mail\MailFormatHelper;
7 use Drupal\Core\Test\AssertMailTrait;
8 use Drupal\Tests\BrowserTestBase;
9 use Drupal\Core\Entity\EntityTypeInterface;
10 use Drupal\Tests\field_ui\Traits\FieldUiTestTrait;
11 use Drupal\user\RoleInterface;
14 * Tests site-wide contact form functionality.
16 * @see \Drupal\Tests\contact\Functional\ContactStorageTest
20 class ContactSitewideTest extends BrowserTestBase {
30 public static $modules = ['text', 'contact', 'field_ui', 'contact_test', 'block', 'error_service_test', 'dblog'];
35 protected function setUp() {
37 $this->drupalPlaceBlock('system_breadcrumb_block');
38 $this->drupalPlaceBlock('local_actions_block');
39 $this->drupalPlaceBlock('page_title_block');
43 * Tests configuration options and the site-wide contact form.
45 public function testSiteWideContact() {
46 // Tests name and email fields for authenticated and anonymous users.
47 $this->drupalLogin($this->drupalCreateUser(['access site-wide contact form']));
48 $this->drupalGet('contact');
50 // Ensure that there is no textfield for name.
51 $this->assertFalse($this->xpath('//input[@name=:name]', [':name' => 'name']));
53 // Ensure that there is no textfield for email.
54 $this->assertFalse($this->xpath('//input[@name=:name]', [':name' => 'mail']));
56 // Logout and retrieve the page as an anonymous user
57 $this->drupalLogout();
58 user_role_grant_permissions('anonymous', ['access site-wide contact form']);
59 $this->drupalGet('contact');
61 // Ensure that there is textfield for name.
62 $this->assertTrue($this->xpath('//input[@name=:name]', [':name' => 'name']));
64 // Ensure that there is textfield for email.
65 $this->assertTrue($this->xpath('//input[@name=:name]', [':name' => 'mail']));
67 // Create and log in administrative user.
68 $admin_user = $this->drupalCreateUser([
69 'access site-wide contact form',
70 'administer contact forms',
72 'administer account settings',
73 'administer contact_message display',
74 'administer contact_message fields',
75 'administer contact_message form display',
77 $this->drupalLogin($admin_user);
79 // Check the presence of expected cache tags.
80 $this->drupalGet('contact');
81 $this->assertCacheTag('config:contact.settings');
84 $this->config('contact.settings')
85 ->set('flood.limit', $flood_limit)
86 ->set('flood.interval', 600)
91 $edit['contact_default_status'] = TRUE;
92 $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
93 $this->assertText(t('The configuration options have been saved.'));
95 $this->drupalGet('admin/structure/contact');
96 // Default form exists.
97 $this->assertLinkByHref('admin/structure/contact/manage/feedback/delete');
98 // User form could not be changed or deleted.
99 // Cannot use ::assertNoLinkByHref as it does partial url matching and with
100 // field_ui enabled admin/structure/contact/manage/personal/fields exists.
101 // @todo: See https://www.drupal.org/node/2031223 for the above.
102 $edit_link = $this->xpath('//a[@href=:href]', [
103 ':href' => \Drupal::url('entity.contact_form.edit_form', ['contact_form' => 'personal']),
105 $this->assertTrue(empty($edit_link), format_string('No link containing href %href found.',
106 ['%href' => 'admin/structure/contact/manage/personal']
108 $this->assertNoLinkByHref('admin/structure/contact/manage/personal/delete');
110 $this->drupalGet('admin/structure/contact/manage/personal');
111 $this->assertResponse(403);
113 // Delete old forms to ensure that new forms are used.
114 $this->deleteContactForms();
115 $this->drupalGet('admin/structure/contact');
116 $this->assertText('Personal', 'Personal form was not deleted');
117 $this->assertNoLinkByHref('admin/structure/contact/manage/feedback');
119 // Ensure that the contact form won't be shown without forms.
120 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
121 $this->drupalLogout();
122 $this->drupalGet('contact');
123 $this->assertResponse(404);
125 $this->drupalLogin($admin_user);
126 $this->drupalGet('contact');
127 $this->assertResponse(200);
128 $this->assertText(t('The contact form has not been configured.'));
129 // Test access personal form via site-wide contact page.
130 $this->drupalGet('contact/personal');
131 $this->assertResponse(403);
134 // Test invalid recipients.
135 $invalid_recipients = ['invalid', 'invalid@', 'invalid@site.', '@site.', '@site.com'];
136 foreach ($invalid_recipients as $invalid_recipient) {
137 $this->addContactForm($this->randomMachineName(16), $this->randomMachineName(16), $invalid_recipient, '', FALSE);
138 $this->assertRaw(t('%recipient is an invalid email address.', ['%recipient' => $invalid_recipient]));
141 // Test validation of empty form and recipients fields.
142 $this->addContactForm('', '', '', '', TRUE);
143 $this->assertText(t('Label field is required.'));
144 $this->assertText(t('Machine-readable name field is required.'));
145 $this->assertText(t('Recipients field is required.'));
147 // Test validation of max_length machine name.
148 $recipients = ['simpletest&@example.com', 'simpletest2@example.com', 'simpletest3@example.com'];
149 $max_length = EntityTypeInterface::BUNDLE_MAX_LENGTH;
150 $max_length_exceeded = $max_length + 1;
151 $this->addContactForm($id = mb_strtolower($this->randomMachineName($max_length_exceeded)), $label = $this->randomMachineName($max_length_exceeded), implode(',', [$recipients[0]]), '', TRUE);
152 $this->assertText(format_string('Machine-readable name cannot be longer than @max characters but is currently @exceeded characters long.', ['@max' => $max_length, '@exceeded' => $max_length_exceeded]));
153 $this->addContactForm($id = mb_strtolower($this->randomMachineName($max_length)), $label = $this->randomMachineName($max_length), implode(',', [$recipients[0]]), '', TRUE);
154 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
156 // Verify that the creation message contains a link to a contact form.
157 $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'contact/']);
158 $this->assert(isset($view_link), 'The message area contains a link to a contact form.');
160 // Create first valid form.
161 $this->addContactForm($id = mb_strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0]]), '', TRUE);
162 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
164 // Verify that the creation message contains a link to a contact form.
165 $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'contact/']);
166 $this->assert(isset($view_link), 'The message area contains a link to a contact form.');
168 // Check that the form was created in site default language.
169 $langcode = $this->config('contact.form.' . $id)->get('langcode');
170 $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
171 $this->assertEqual($langcode, $default_langcode);
173 // Make sure the newly created form is included in the list of forms.
174 $this->assertNoUniqueText($label, 'New form included in forms list.');
176 // Ensure that the recipient email is escaped on the listing.
177 $this->drupalGet('admin/structure/contact');
178 $this->assertEscaped($recipients[0]);
180 // Test update contact form.
181 $this->updateContactForm($id, $label = $this->randomMachineName(16), $recipients_str = implode(',', [$recipients[0], $recipients[1]]), $reply = $this->randomMachineName(30), FALSE, 'Your message has been sent.', '/user');
182 $config = $this->config('contact.form.' . $id)->get();
183 $this->assertEqual($config['label'], $label);
184 $this->assertEqual($config['recipients'], [$recipients[0], $recipients[1]]);
185 $this->assertEqual($config['reply'], $reply);
186 $this->assertNotEqual($id, $this->config('contact.settings')->get('default_form'));
187 $this->assertText(t('Contact form @label has been updated.', ['@label' => $label]));
188 // Ensure the label is displayed on the contact page for this form.
189 $this->drupalGet('contact/' . $id);
190 $this->assertText($label);
192 // Reset the form back to be the default form.
193 $this->config('contact.settings')->set('default_form', $id)->save();
195 // Ensure that the contact form is shown without a form selection input.
196 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
197 $this->drupalLogout();
198 $this->drupalGet('contact');
199 $this->assertText(t('Your email address'));
200 $this->assertNoText(t('Form'));
201 $this->drupalLogin($admin_user);
204 $this->addContactForm(mb_strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0], $recipients[1]]), '', FALSE);
205 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
207 $this->addContactForm($name = mb_strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0], $recipients[1], $recipients[2]]), '', FALSE);
208 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
210 // Try adding a form that already exists.
211 $this->addContactForm($name, $label, '', '', FALSE);
212 $this->assertNoText(t('Contact form @label has been added.', ['@label' => $label]));
213 $this->assertRaw(t('The machine-readable name is already in use. It must be unique.'));
215 $this->drupalLogout();
217 // Check to see that anonymous user cannot see contact page without permission.
218 user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
219 $this->drupalGet('contact');
220 $this->assertResponse(403);
222 // Give anonymous user permission and see that page is viewable.
223 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
224 $this->drupalGet('contact');
225 $this->assertResponse(200);
227 // Submit contact form with invalid values.
228 $this->submitContact('', $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
229 $this->assertText(t('Your name field is required.'));
231 $this->submitContact($this->randomMachineName(16), '', $this->randomMachineName(16), $id, $this->randomMachineName(64));
232 $this->assertText(t('Your email address field is required.'));
234 $this->submitContact($this->randomMachineName(16), $invalid_recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
235 $this->assertRaw(t('The email address %mail is not valid.', ['%mail' => 'invalid']));
237 $this->submitContact($this->randomMachineName(16), $recipients[0], '', $id, $this->randomMachineName(64));
238 $this->assertText(t('Subject field is required.'));
240 $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, '');
241 $this->assertText(t('Message field is required.'));
243 // Test contact form with no default form selected.
244 $this->config('contact.settings')
245 ->set('default_form', '')
247 $this->drupalGet('contact');
248 $this->assertResponse(404);
250 // Try to access contact form with non-existing form IDs.
251 $this->drupalGet('contact/0');
252 $this->assertResponse(404);
253 $this->drupalGet('contact/' . $this->randomMachineName());
254 $this->assertResponse(404);
256 // Submit contact form with correct values and check flood interval.
257 for ($i = 0; $i < $flood_limit; $i++) {
258 $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
259 $this->assertText(t('Your message has been sent.'));
261 // Submit contact form one over limit.
262 $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
263 $this->assertRaw(t('You cannot send more than %number messages in 10 min. Try again later.', ['%number' => $this->config('contact.settings')->get('flood.limit')]));
265 // Test listing controller.
266 $this->drupalLogin($admin_user);
268 $this->deleteContactForms();
270 $label = $this->randomMachineName(16);
271 $recipients = implode(',', [$recipients[0], $recipients[1], $recipients[2]]);
272 $contact_form = mb_strtolower($this->randomMachineName(16));
273 $this->addContactForm($contact_form, $label, $recipients, '', FALSE);
274 $this->drupalGet('admin/structure/contact');
275 $this->clickLink(t('Edit'));
276 $this->assertResponse(200);
277 $this->assertFieldByName('label', $label);
279 // Test field UI and field integration.
280 $this->drupalGet('admin/structure/contact');
282 $view_link = $this->xpath('//table/tbody/tr/td/a[contains(@href, :href) and text()=:text]', [
283 ':href' => \Drupal::url('entity.contact_form.canonical', ['contact_form' => $contact_form]),
287 $this->assertTrue(!empty($view_link), 'Contact listing links to contact form.');
289 // Find out in which row the form we want to add a field to is.
290 foreach ($this->xpath('//table/tbody/tr') as $row) {
291 if ($row->findLink($label)) {
292 $row->clickLink('Manage fields');
297 $this->assertResponse(200);
298 $this->clickLink(t('Add field'));
299 $this->assertResponse(200);
301 // Create a simple textfield.
302 $field_name = mb_strtolower($this->randomMachineName());
303 $field_label = $this->randomMachineName();
304 $this->fieldUIAddNewField(NULL, $field_name, $field_label, 'text');
305 $field_name = 'field_' . $field_name;
307 // Check preview field can be ordered.
308 $this->drupalGet('admin/structure/contact/manage/' . $contact_form . '/form-display');
309 $this->assertText(t('Preview'));
311 // Check that the field is displayed.
312 $this->drupalGet('contact/' . $contact_form);
313 $this->assertText($field_label);
315 // Submit the contact form and verify the content.
317 'subject[0][value]' => $this->randomMachineName(),
318 'message[0][value]' => $this->randomMachineName(),
319 $field_name . '[0][value]' => $this->randomMachineName(),
321 $this->drupalPostForm(NULL, $edit, t('Send message'));
322 $mails = $this->getMails();
323 $mail = array_pop($mails);
324 $this->assertEqual($mail['subject'], t('[@label] @subject', ['@label' => $label, '@subject' => $edit['subject[0][value]']]));
325 $this->assertTrue(strpos($mail['body'], $field_label));
326 $this->assertTrue(strpos($mail['body'], $edit[$field_name . '[0][value]']));
328 // Test messages and redirect.
329 /** @var \Drupal\contact\ContactFormInterface $form */
330 $form = ContactForm::load($contact_form);
331 $form->setMessage('Thanks for your submission.');
332 $form->setRedirectPath('/user/' . $admin_user->id());
334 // Check that the field is displayed.
335 $this->drupalGet('contact/' . $contact_form);
337 // Submit the contact form and verify the content.
339 'subject[0][value]' => $this->randomMachineName(),
340 'message[0][value]' => $this->randomMachineName(),
341 $field_name . '[0][value]' => $this->randomMachineName(),
343 $this->drupalPostForm(NULL, $edit, t('Send message'));
344 $this->assertText('Thanks for your submission.');
345 $this->assertUrl('user/' . $admin_user->id());
347 // Test Empty message.
348 /** @var \Drupal\contact\ContactFormInterface $form */
349 $form = ContactForm::load($contact_form);
350 $form->setMessage('');
351 $form->setRedirectPath('/user/' . $admin_user->id());
353 $this->drupalGet('admin/structure/contact/manage/' . $contact_form);
354 // Check that the field is displayed.
355 $this->drupalGet('contact/' . $contact_form);
357 // Submit the contact form and verify the content.
359 'subject[0][value]' => $this->randomMachineName(),
360 'message[0][value]' => $this->randomMachineName(),
361 $field_name . '[0][value]' => $this->randomMachineName(),
363 $this->drupalPostForm(NULL, $edit, t('Send message'));
364 $result = $this->xpath('//div[@role=:role]', [':role' => 'contentinfo']);
365 $this->assertEqual(count($result), 0, 'Messages not found.');
366 $this->assertUrl('user/' . $admin_user->id());
368 // Test preview and visibility of the message field and label. Submit the
369 // contact form and verify the content.
371 'subject[0][value]' => $this->randomMachineName(),
372 'message[0][value]' => $this->randomMachineName(),
373 $field_name . '[0][value]' => $this->randomMachineName(),
375 $this->drupalPostForm($form->toUrl('canonical'), $edit, t('Preview'));
377 // Message is now by default displayed twice, once for the form element and
378 // once for the viewed message.
379 $page_text = $this->getSession()->getPage()->getText();
380 $this->assertGreaterThan(1, substr_count($page_text, t('Message')));
381 $this->assertSession()->responseContains('class="field field--name-message field--type-string-long field--label-above');
382 $this->assertSession()->pageTextContains($edit['message[0][value]']);
384 // Hide the message field label.
386 'fields[message][label]' => 'hidden',
388 $this->drupalPostForm('admin/structure/contact/manage/' . $contact_form . '/display', $display_edit, t('Save'));
390 $this->drupalPostForm($form->toUrl('canonical'), $edit, t('Preview'));
391 // Message should only be displayed once now.
392 $page_text = $this->getSession()->getPage()->getText();
393 $this->assertEquals(1, substr_count($page_text, t('Message')));
394 $this->assertSession()->responseContains('class="field field--name-message field--type-string-long field--label-hidden field__item">');
395 $this->assertSession()->pageTextContains($edit['message[0][value]']);
399 * Tests auto-reply on the site-wide contact form.
401 public function testAutoReply() {
402 // Create and log in administrative user.
403 $admin_user = $this->drupalCreateUser([
404 'access site-wide contact form',
405 'administer contact forms',
406 'administer permissions',
408 'access site reports',
410 $this->drupalLogin($admin_user);
412 // Set up three forms, 2 with an auto-reply and one without.
413 $foo_autoreply = $this->randomMachineName(40);
414 $bar_autoreply = $this->randomMachineName(40);
415 $this->addContactForm('foo', 'foo', 'foo@example.com', $foo_autoreply, FALSE);
416 $this->addContactForm('bar', 'bar', 'bar@example.com', $bar_autoreply, FALSE);
417 $this->addContactForm('no_autoreply', 'no_autoreply', 'bar@example.com', '', FALSE);
419 // Log the current user out in order to test the name and email fields.
420 $this->drupalLogout();
421 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
423 // Test the auto-reply for form 'foo'.
424 $email = $this->randomMachineName(32) . '@example.com';
425 $subject = $this->randomMachineName(64);
426 $this->submitContact($this->randomMachineName(16), $email, $subject, 'foo', $this->randomString(128));
428 // We are testing the auto-reply, so there should be one email going to the sender.
429 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
430 $this->assertEqual(count($captured_emails), 1);
431 $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($foo_autoreply)));
433 // Test the auto-reply for form 'bar'.
434 $email = $this->randomMachineName(32) . '@example.com';
435 $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'bar', $this->randomString(128));
437 // Auto-reply for form 'bar' should result in one auto-reply email to the sender.
438 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
439 $this->assertEqual(count($captured_emails), 1);
440 $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($bar_autoreply)));
442 // Verify that no auto-reply is sent when the auto-reply field is left blank.
443 $email = $this->randomMachineName(32) . '@example.com';
444 $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'no_autoreply', $this->randomString(128));
445 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
446 $this->assertEqual(count($captured_emails), 0);
448 // Verify that the current error message doesn't show, that the auto-reply
449 // doesn't get sent and the correct silent error gets logged.
451 entity_get_form_display('contact_message', 'foo', 'default')
452 ->removeComponent('mail')
454 $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'foo', $this->randomString(128));
455 $this->assertNoText('Unable to send email. Contact the site administrator if the problem persists.');
456 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
457 $this->assertEqual(count($captured_emails), 0);
458 $this->drupalLogin($admin_user);
459 $this->drupalGet('admin/reports/dblog');
460 $this->assertRaw('Error sending auto-reply, missing sender e-mail address in foo');
467 * The form machine name.
468 * @param string $label
470 * @param string $recipients
471 * The list of recipient email addresses.
472 * @param string $reply
473 * The auto-reply text that is sent to a user upon completing the contact
475 * @param bool $selected
476 * A Boolean indicating whether the form should be selected by default.
477 * @param string $message
478 * The message that will be displayed to a user upon completing the contact
480 * @param array $third_party_settings
481 * Array of third party settings to be added to the posted form data.
483 public function addContactForm($id, $label, $recipients, $reply, $selected, $message = 'Your message has been sent.', $third_party_settings = []) {
485 $edit['label'] = $label;
487 $edit['message'] = $message;
488 $edit['recipients'] = $recipients;
489 $edit['reply'] = $reply;
490 $edit['selected'] = ($selected ? TRUE : FALSE);
491 $edit += $third_party_settings;
492 $this->drupalPostForm('admin/structure/contact/add', $edit, t('Save'));
499 * The form machine name.
500 * @param string $label
502 * @param string $recipients
503 * The list of recipient email addresses.
504 * @param string $reply
505 * The auto-reply text that is sent to a user upon completing the contact
507 * @param bool $selected
508 * A Boolean indicating whether the form should be selected by default.
509 * @param string $message
510 * The message that will be displayed to a user upon completing the contact
512 * @param string $redirect
513 * The path where user will be redirect after this form has been submitted..
515 public function updateContactForm($id, $label, $recipients, $reply, $selected, $message = 'Your message has been sent.', $redirect = '/') {
517 $edit['label'] = $label;
518 $edit['recipients'] = $recipients;
519 $edit['reply'] = $reply;
520 $edit['selected'] = ($selected ? TRUE : FALSE);
521 $edit['message'] = $message;
522 $edit['redirect'] = $redirect;
523 $this->drupalPostForm("admin/structure/contact/manage/$id", $edit, t('Save'));
527 * Submits the contact form.
529 * @param string $name
530 * The name of the sender.
531 * @param string $mail
532 * The email address of the sender.
533 * @param string $subject
534 * The subject of the message.
536 * The form ID of the message.
537 * @param string $message
540 public function submitContact($name, $mail, $subject, $id, $message) {
542 $edit['name'] = $name;
543 $edit['mail'] = $mail;
544 $edit['subject[0][value]'] = $subject;
545 $edit['message[0][value]'] = $message;
546 if ($id == $this->config('contact.settings')->get('default_form')) {
547 $this->drupalPostForm('contact', $edit, t('Send message'));
550 $this->drupalPostForm('contact/' . $id, $edit, t('Send message'));
557 public function deleteContactForms() {
558 $contact_forms = ContactForm::loadMultiple();;
559 foreach ($contact_forms as $id => $contact_form) {
560 if ($id == 'personal') {
561 // Personal form could not be deleted.
562 $this->drupalGet("admin/structure/contact/manage/$id/delete");
563 $this->assertResponse(403);
566 $this->drupalPostForm("admin/structure/contact/manage/$id/delete", [], t('Delete'));
567 $this->assertRaw(t('The contact form %label has been deleted.', ['%label' => $contact_form->label()]));
568 $this->assertFalse(ContactForm::load($id), format_string('Form %contact_form not found', ['%contact_form' => $contact_form->label()]));