3 namespace Drupal\Tests\contact\Functional;
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\contact\Entity\ContactForm;
7 use Drupal\Core\Mail\MailFormatHelper;
8 use Drupal\Core\Test\AssertMailTrait;
9 use Drupal\field_ui\Tests\FieldUiTestTrait;
10 use Drupal\Tests\BrowserTestBase;
11 use Drupal\Core\Entity\EntityTypeInterface;
12 use Drupal\user\RoleInterface;
15 * Tests site-wide contact form functionality.
17 * @see \Drupal\Tests\contact\Functional\ContactStorageTest
21 class ContactSitewideTest extends BrowserTestBase {
31 public static $modules = ['text', 'contact', 'field_ui', 'contact_test', 'block', 'error_service_test', 'dblog'];
36 protected function setUp() {
38 $this->drupalPlaceBlock('system_breadcrumb_block');
39 $this->drupalPlaceBlock('local_actions_block');
40 $this->drupalPlaceBlock('page_title_block');
44 * Tests configuration options and the site-wide contact form.
46 public function testSiteWideContact() {
47 // Tests name and email fields for authenticated and anonymous users.
48 $this->drupalLogin($this->drupalCreateUser(['access site-wide contact form']));
49 $this->drupalGet('contact');
51 // Ensure that there is no textfield for name.
52 $this->assertFalse($this->xpath('//input[@name=:name]', [':name' => 'name']));
54 // Ensure that there is no textfield for email.
55 $this->assertFalse($this->xpath('//input[@name=:name]', [':name' => 'mail']));
57 // Logout and retrieve the page as an anonymous user
58 $this->drupalLogout();
59 user_role_grant_permissions('anonymous', ['access site-wide contact form']);
60 $this->drupalGet('contact');
62 // Ensure that there is textfield for name.
63 $this->assertTrue($this->xpath('//input[@name=:name]', [':name' => 'name']));
65 // Ensure that there is textfield for email.
66 $this->assertTrue($this->xpath('//input[@name=:name]', [':name' => 'mail']));
68 // Create and log in administrative user.
69 $admin_user = $this->drupalCreateUser([
70 'access site-wide contact form',
71 'administer contact forms',
73 'administer account settings',
74 'administer contact_message display',
75 'administer contact_message fields',
76 'administer contact_message form display',
78 $this->drupalLogin($admin_user);
80 // Check the presence of expected cache tags.
81 $this->drupalGet('contact');
82 $this->assertCacheTag('config:contact.settings');
85 $this->config('contact.settings')
86 ->set('flood.limit', $flood_limit)
87 ->set('flood.interval', 600)
92 $edit['contact_default_status'] = TRUE;
93 $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
94 $this->assertText(t('The configuration options have been saved.'));
96 $this->drupalGet('admin/structure/contact');
97 // Default form exists.
98 $this->assertLinkByHref('admin/structure/contact/manage/feedback/delete');
99 // User form could not be changed or deleted.
100 // Cannot use ::assertNoLinkByHref as it does partial url matching and with
101 // field_ui enabled admin/structure/contact/manage/personal/fields exists.
102 // @todo: See https://www.drupal.org/node/2031223 for the above.
103 $edit_link = $this->xpath('//a[@href=:href]', [
104 ':href' => \Drupal::url('entity.contact_form.edit_form', ['contact_form' => 'personal'])
106 $this->assertTrue(empty($edit_link), format_string('No link containing href %href found.',
107 ['%href' => 'admin/structure/contact/manage/personal']
109 $this->assertNoLinkByHref('admin/structure/contact/manage/personal/delete');
111 $this->drupalGet('admin/structure/contact/manage/personal');
112 $this->assertResponse(403);
114 // Delete old forms to ensure that new forms are used.
115 $this->deleteContactForms();
116 $this->drupalGet('admin/structure/contact');
117 $this->assertText('Personal', 'Personal form was not deleted');
118 $this->assertNoLinkByHref('admin/structure/contact/manage/feedback');
120 // Ensure that the contact form won't be shown without forms.
121 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
122 $this->drupalLogout();
123 $this->drupalGet('contact');
124 $this->assertResponse(404);
126 $this->drupalLogin($admin_user);
127 $this->drupalGet('contact');
128 $this->assertResponse(200);
129 $this->assertText(t('The contact form has not been configured.'));
130 // Test access personal form via site-wide contact page.
131 $this->drupalGet('contact/personal');
132 $this->assertResponse(403);
135 // Test invalid recipients.
136 $invalid_recipients = ['invalid', 'invalid@', 'invalid@site.', '@site.', '@site.com'];
137 foreach ($invalid_recipients as $invalid_recipient) {
138 $this->addContactForm($this->randomMachineName(16), $this->randomMachineName(16), $invalid_recipient, '', FALSE);
139 $this->assertRaw(t('%recipient is an invalid email address.', ['%recipient' => $invalid_recipient]));
142 // Test validation of empty form and recipients fields.
143 $this->addContactForm('', '', '', '', TRUE);
144 $this->assertText(t('Label field is required.'));
145 $this->assertText(t('Machine-readable name field is required.'));
146 $this->assertText(t('Recipients field is required.'));
148 // Test validation of max_length machine name.
149 $recipients = ['simpletest&@example.com', 'simpletest2@example.com', 'simpletest3@example.com'];
150 $max_length = EntityTypeInterface::BUNDLE_MAX_LENGTH;
151 $max_length_exceeded = $max_length + 1;
152 $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length_exceeded)), $label = $this->randomMachineName($max_length_exceeded), implode(',', [$recipients[0]]), '', TRUE);
153 $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]));
154 $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length)), $label = $this->randomMachineName($max_length), implode(',', [$recipients[0]]), '', TRUE);
155 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
157 // Verify that the creation message contains a link to a contact form.
158 $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'contact/']);
159 $this->assert(isset($view_link), 'The message area contains a link to a contact form.');
161 // Create first valid form.
162 $this->addContactForm($id = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0]]), '', TRUE);
163 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
165 // Verify that the creation message contains a link to a contact form.
166 $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'contact/']);
167 $this->assert(isset($view_link), 'The message area contains a link to a contact form.');
169 // Check that the form was created in site default language.
170 $langcode = $this->config('contact.form.' . $id)->get('langcode');
171 $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
172 $this->assertEqual($langcode, $default_langcode);
174 // Make sure the newly created form is included in the list of forms.
175 $this->assertNoUniqueText($label, 'New form included in forms list.');
177 // Ensure that the recipient email is escaped on the listing.
178 $this->drupalGet('admin/structure/contact');
179 $this->assertEscaped($recipients[0]);
181 // Test update contact form.
182 $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');
183 $config = $this->config('contact.form.' . $id)->get();
184 $this->assertEqual($config['label'], $label);
185 $this->assertEqual($config['recipients'], [$recipients[0], $recipients[1]]);
186 $this->assertEqual($config['reply'], $reply);
187 $this->assertNotEqual($id, $this->config('contact.settings')->get('default_form'));
188 $this->assertText(t('Contact form @label has been updated.', ['@label' => $label]));
189 // Ensure the label is displayed on the contact page for this form.
190 $this->drupalGet('contact/' . $id);
191 $this->assertText($label);
193 // Reset the form back to be the default form.
194 $this->config('contact.settings')->set('default_form', $id)->save();
196 // Ensure that the contact form is shown without a form selection input.
197 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
198 $this->drupalLogout();
199 $this->drupalGet('contact');
200 $this->assertText(t('Your email address'));
201 $this->assertNoText(t('Form'));
202 $this->drupalLogin($admin_user);
205 $this->addContactForm(Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0], $recipients[1]]), '', FALSE);
206 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
208 $this->addContactForm($name = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0], $recipients[1], $recipients[2]]), '', FALSE);
209 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
211 // Try adding a form that already exists.
212 $this->addContactForm($name, $label, '', '', FALSE);
213 $this->assertNoText(t('Contact form @label has been added.', ['@label' => $label]));
214 $this->assertRaw(t('The machine-readable name is already in use. It must be unique.'));
216 $this->drupalLogout();
218 // Check to see that anonymous user cannot see contact page without permission.
219 user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
220 $this->drupalGet('contact');
221 $this->assertResponse(403);
223 // Give anonymous user permission and see that page is viewable.
224 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
225 $this->drupalGet('contact');
226 $this->assertResponse(200);
228 // Submit contact form with invalid values.
229 $this->submitContact('', $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
230 $this->assertText(t('Your name field is required.'));
232 $this->submitContact($this->randomMachineName(16), '', $this->randomMachineName(16), $id, $this->randomMachineName(64));
233 $this->assertText(t('Your email address field is required.'));
235 $this->submitContact($this->randomMachineName(16), $invalid_recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
236 $this->assertRaw(t('The email address %mail is not valid.', ['%mail' => 'invalid']));
238 $this->submitContact($this->randomMachineName(16), $recipients[0], '', $id, $this->randomMachineName(64));
239 $this->assertText(t('Subject field is required.'));
241 $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, '');
242 $this->assertText(t('Message field is required.'));
244 // Test contact form with no default form selected.
245 $this->config('contact.settings')
246 ->set('default_form', '')
248 $this->drupalGet('contact');
249 $this->assertResponse(404);
251 // Try to access contact form with non-existing form IDs.
252 $this->drupalGet('contact/0');
253 $this->assertResponse(404);
254 $this->drupalGet('contact/' . $this->randomMachineName());
255 $this->assertResponse(404);
257 // Submit contact form with correct values and check flood interval.
258 for ($i = 0; $i < $flood_limit; $i++) {
259 $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
260 $this->assertText(t('Your message has been sent.'));
262 // Submit contact form one over limit.
263 $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
264 $this->assertRaw(t('You cannot send more than %number messages in 10 min. Try again later.', ['%number' => $this->config('contact.settings')->get('flood.limit')]));
266 // Test listing controller.
267 $this->drupalLogin($admin_user);
269 $this->deleteContactForms();
271 $label = $this->randomMachineName(16);
272 $recipients = implode(',', [$recipients[0], $recipients[1], $recipients[2]]);
273 $contact_form = Unicode::strtolower($this->randomMachineName(16));
274 $this->addContactForm($contact_form, $label, $recipients, '', FALSE);
275 $this->drupalGet('admin/structure/contact');
276 $this->clickLink(t('Edit'));
277 $this->assertResponse(200);
278 $this->assertFieldByName('label', $label);
280 // Test field UI and field integration.
281 $this->drupalGet('admin/structure/contact');
283 $view_link = $this->xpath('//table/tbody/tr/td/a[contains(@href, :href) and text()=:text]', [
284 ':href' => \Drupal::url('entity.contact_form.canonical', ['contact_form' => $contact_form]),
288 $this->assertTrue(!empty($view_link), 'Contact listing links to contact form.');
290 // Find out in which row the form we want to add a field to is.
291 foreach ($this->xpath('//table/tbody/tr') as $row) {
292 if ($row->findLink($label)) {
293 $row->clickLink('Manage fields');
298 $this->assertResponse(200);
299 $this->clickLink(t('Add field'));
300 $this->assertResponse(200);
302 // Create a simple textfield.
303 $field_name = Unicode::strtolower($this->randomMachineName());
304 $field_label = $this->randomMachineName();
305 $this->fieldUIAddNewField(NULL, $field_name, $field_label, 'text');
306 $field_name = 'field_' . $field_name;
308 // Check preview field can be ordered.
309 $this->drupalGet('admin/structure/contact/manage/' . $contact_form . '/form-display');
310 $this->assertText(t('Preview'));
312 // Check that the field is displayed.
313 $this->drupalGet('contact/' . $contact_form);
314 $this->assertText($field_label);
316 // Submit the contact form and verify the content.
318 'subject[0][value]' => $this->randomMachineName(),
319 'message[0][value]' => $this->randomMachineName(),
320 $field_name . '[0][value]' => $this->randomMachineName(),
322 $this->drupalPostForm(NULL, $edit, t('Send message'));
323 $mails = $this->getMails();
324 $mail = array_pop($mails);
325 $this->assertEqual($mail['subject'], t('[@label] @subject', ['@label' => $label, '@subject' => $edit['subject[0][value]']]));
326 $this->assertTrue(strpos($mail['body'], $field_label));
327 $this->assertTrue(strpos($mail['body'], $edit[$field_name . '[0][value]']));
329 // Test messages and redirect.
330 /** @var \Drupal\contact\ContactFormInterface $form */
331 $form = ContactForm::load($contact_form);
332 $form->setMessage('Thanks for your submission.');
333 $form->setRedirectPath('/user/' . $admin_user->id());
335 // Check that the field is displayed.
336 $this->drupalGet('contact/' . $contact_form);
338 // Submit the contact form and verify the content.
340 'subject[0][value]' => $this->randomMachineName(),
341 'message[0][value]' => $this->randomMachineName(),
342 $field_name . '[0][value]' => $this->randomMachineName(),
344 $this->drupalPostForm(NULL, $edit, t('Send message'));
345 $this->assertText('Thanks for your submission.');
346 $this->assertUrl('user/' . $admin_user->id());
348 // Test Empty message.
349 /** @var \Drupal\contact\ContactFormInterface $form */
350 $form = ContactForm::load($contact_form);
351 $form->setMessage('');
352 $form->setRedirectPath('/user/' . $admin_user->id());
354 $this->drupalGet('admin/structure/contact/manage/' . $contact_form);
355 // Check that the field is displayed.
356 $this->drupalGet('contact/' . $contact_form);
358 // Submit the contact form and verify the content.
360 'subject[0][value]' => $this->randomMachineName(),
361 'message[0][value]' => $this->randomMachineName(),
362 $field_name . '[0][value]' => $this->randomMachineName(),
364 $this->drupalPostForm(NULL, $edit, t('Send message'));
365 $result = $this->xpath('//div[@role=:role]', [':role' => 'contentinfo']);
366 $this->assertEqual(count($result), 0, 'Messages not found.');
367 $this->assertUrl('user/' . $admin_user->id());
369 // Test preview and visibility of the message field and label. Submit the
370 // contact form and verify the content.
372 'subject[0][value]' => $this->randomMachineName(),
373 'message[0][value]' => $this->randomMachineName(),
374 $field_name . '[0][value]' => $this->randomMachineName(),
376 $this->drupalPostForm($form->toUrl('canonical'), $edit, t('Preview'));
378 // Message is now by default displayed twice, once for the form element and
379 // once for the viewed message.
380 $page_text = $this->getSession()->getPage()->getText();
381 $this->assertGreaterThan(1, substr_count($page_text, t('Message')));
382 $this->assertSession()->responseContains('class="field field--name-message field--type-string-long field--label-above');
383 $this->assertSession()->pageTextContains($edit['message[0][value]']);
385 // Hide the message field label.
387 'fields[message][label]' => 'hidden',
389 $this->drupalPostForm('admin/structure/contact/manage/' . $contact_form . '/display', $display_edit, t('Save'));
391 $this->drupalPostForm($form->toUrl('canonical'), $edit, t('Preview'));
392 // Message should only be displayed once now.
393 $page_text = $this->getSession()->getPage()->getText();
394 $this->assertEquals(1, substr_count($page_text, t('Message')));
395 $this->assertSession()->responseContains('class="field field--name-message field--type-string-long field--label-hidden field__item">');
396 $this->assertSession()->pageTextContains($edit['message[0][value]']);
400 * Tests auto-reply on the site-wide contact form.
402 public function testAutoReply() {
403 // Create and log in administrative user.
404 $admin_user = $this->drupalCreateUser([
405 'access site-wide contact form',
406 'administer contact forms',
407 'administer permissions',
409 'access site reports'
411 $this->drupalLogin($admin_user);
413 // Set up three forms, 2 with an auto-reply and one without.
414 $foo_autoreply = $this->randomMachineName(40);
415 $bar_autoreply = $this->randomMachineName(40);
416 $this->addContactForm('foo', 'foo', 'foo@example.com', $foo_autoreply, FALSE);
417 $this->addContactForm('bar', 'bar', 'bar@example.com', $bar_autoreply, FALSE);
418 $this->addContactForm('no_autoreply', 'no_autoreply', 'bar@example.com', '', FALSE);
420 // Log the current user out in order to test the name and email fields.
421 $this->drupalLogout();
422 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
424 // Test the auto-reply for form 'foo'.
425 $email = $this->randomMachineName(32) . '@example.com';
426 $subject = $this->randomMachineName(64);
427 $this->submitContact($this->randomMachineName(16), $email, $subject, 'foo', $this->randomString(128));
429 // We are testing the auto-reply, so there should be one email going to the sender.
430 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
431 $this->assertEqual(count($captured_emails), 1);
432 $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($foo_autoreply)));
434 // Test the auto-reply for form 'bar'.
435 $email = $this->randomMachineName(32) . '@example.com';
436 $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'bar', $this->randomString(128));
438 // Auto-reply for form 'bar' should result in one auto-reply email to the sender.
439 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
440 $this->assertEqual(count($captured_emails), 1);
441 $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($bar_autoreply)));
443 // Verify that no auto-reply is sent when the auto-reply field is left blank.
444 $email = $this->randomMachineName(32) . '@example.com';
445 $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'no_autoreply', $this->randomString(128));
446 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
447 $this->assertEqual(count($captured_emails), 0);
449 // Verify that the current error message doesn't show, that the auto-reply
450 // doesn't get sent and the correct silent error gets logged.
452 entity_get_form_display('contact_message', 'foo', 'default')
453 ->removeComponent('mail')
455 $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'foo', $this->randomString(128));
456 $this->assertNoText('Unable to send email. Contact the site administrator if the problem persists.');
457 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
458 $this->assertEqual(count($captured_emails), 0);
459 $this->drupalLogin($admin_user);
460 $this->drupalGet('admin/reports/dblog');
461 $this->assertRaw('Error sending auto-reply, missing sender e-mail address in foo');
468 * The form machine name.
469 * @param string $label
471 * @param string $recipients
472 * The list of recipient email addresses.
473 * @param string $reply
474 * The auto-reply text that is sent to a user upon completing the contact
476 * @param bool $selected
477 * A Boolean indicating whether the form should be selected by default.
478 * @param string $message
479 * The message that will be displayed to a user upon completing the contact
481 * @param array $third_party_settings
482 * Array of third party settings to be added to the posted form data.
484 public function addContactForm($id, $label, $recipients, $reply, $selected, $message = 'Your message has been sent.', $third_party_settings = []) {
486 $edit['label'] = $label;
488 $edit['message'] = $message;
489 $edit['recipients'] = $recipients;
490 $edit['reply'] = $reply;
491 $edit['selected'] = ($selected ? TRUE : FALSE);
492 $edit += $third_party_settings;
493 $this->drupalPostForm('admin/structure/contact/add', $edit, t('Save'));
500 * The form machine name.
501 * @param string $label
503 * @param string $recipients
504 * The list of recipient email addresses.
505 * @param string $reply
506 * The auto-reply text that is sent to a user upon completing the contact
508 * @param bool $selected
509 * A Boolean indicating whether the form should be selected by default.
510 * @param string $message
511 * The message that will be displayed to a user upon completing the contact
513 * @param string $redirect
514 * The path where user will be redirect after this form has been submitted..
516 public function updateContactForm($id, $label, $recipients, $reply, $selected, $message = 'Your message has been sent.', $redirect = '/') {
518 $edit['label'] = $label;
519 $edit['recipients'] = $recipients;
520 $edit['reply'] = $reply;
521 $edit['selected'] = ($selected ? TRUE : FALSE);
522 $edit['message'] = $message;
523 $edit['redirect'] = $redirect;
524 $this->drupalPostForm("admin/structure/contact/manage/$id", $edit, t('Save'));
528 * Submits the contact form.
530 * @param string $name
531 * The name of the sender.
532 * @param string $mail
533 * The email address of the sender.
534 * @param string $subject
535 * The subject of the message.
537 * The form ID of the message.
538 * @param string $message
541 public function submitContact($name, $mail, $subject, $id, $message) {
543 $edit['name'] = $name;
544 $edit['mail'] = $mail;
545 $edit['subject[0][value]'] = $subject;
546 $edit['message[0][value]'] = $message;
547 if ($id == $this->config('contact.settings')->get('default_form')) {
548 $this->drupalPostForm('contact', $edit, t('Send message'));
551 $this->drupalPostForm('contact/' . $id, $edit, t('Send message'));
558 public function deleteContactForms() {
559 $contact_forms = ContactForm::loadMultiple();;
560 foreach ($contact_forms as $id => $contact_form) {
561 if ($id == 'personal') {
562 // Personal form could not be deleted.
563 $this->drupalGet("admin/structure/contact/manage/$id/delete");
564 $this->assertResponse(403);
567 $this->drupalPostForm("admin/structure/contact/manage/$id/delete", [], t('Delete'));
568 $this->assertRaw(t('The contact form %label has been deleted.', ['%label' => $contact_form->label()]));
569 $this->assertFalse(ContactForm::load($id), format_string('Form %contact_form not found', ['%contact_form' => $contact_form->label()]));