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 // Create and log in administrative user.
48 $admin_user = $this->drupalCreateUser([
49 'access site-wide contact form',
50 'administer contact forms',
52 'administer account settings',
53 'administer contact_message display',
54 'administer contact_message fields',
55 'administer contact_message form display',
57 $this->drupalLogin($admin_user);
59 // Check the presence of expected cache tags.
60 $this->drupalGet('contact');
61 $this->assertCacheTag('config:contact.settings');
64 $this->config('contact.settings')
65 ->set('flood.limit', $flood_limit)
66 ->set('flood.interval', 600)
71 $edit['contact_default_status'] = TRUE;
72 $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
73 $this->assertText(t('The configuration options have been saved.'));
75 $this->drupalGet('admin/structure/contact');
76 // Default form exists.
77 $this->assertLinkByHref('admin/structure/contact/manage/feedback/delete');
78 // User form could not be changed or deleted.
79 // Cannot use ::assertNoLinkByHref as it does partial url matching and with
80 // field_ui enabled admin/structure/contact/manage/personal/fields exists.
81 // @todo: See https://www.drupal.org/node/2031223 for the above.
82 $edit_link = $this->xpath('//a[@href=:href]', [
83 ':href' => \Drupal::url('entity.contact_form.edit_form', ['contact_form' => 'personal'])
85 $this->assertTrue(empty($edit_link), format_string('No link containing href %href found.',
86 ['%href' => 'admin/structure/contact/manage/personal']
88 $this->assertNoLinkByHref('admin/structure/contact/manage/personal/delete');
90 $this->drupalGet('admin/structure/contact/manage/personal');
91 $this->assertResponse(403);
93 // Delete old forms to ensure that new forms are used.
94 $this->deleteContactForms();
95 $this->drupalGet('admin/structure/contact');
96 $this->assertText('Personal', 'Personal form was not deleted');
97 $this->assertNoLinkByHref('admin/structure/contact/manage/feedback');
99 // Ensure that the contact form won't be shown without forms.
100 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
101 $this->drupalLogout();
102 $this->drupalGet('contact');
103 $this->assertResponse(404);
105 $this->drupalLogin($admin_user);
106 $this->drupalGet('contact');
107 $this->assertResponse(200);
108 $this->assertText(t('The contact form has not been configured.'));
109 // Test access personal form via site-wide contact page.
110 $this->drupalGet('contact/personal');
111 $this->assertResponse(403);
114 // Test invalid recipients.
115 $invalid_recipients = ['invalid', 'invalid@', 'invalid@site.', '@site.', '@site.com'];
116 foreach ($invalid_recipients as $invalid_recipient) {
117 $this->addContactForm($this->randomMachineName(16), $this->randomMachineName(16), $invalid_recipient, '', FALSE);
118 $this->assertRaw(t('%recipient is an invalid email address.', ['%recipient' => $invalid_recipient]));
121 // Test validation of empty form and recipients fields.
122 $this->addContactForm('', '', '', '', TRUE);
123 $this->assertText(t('Label field is required.'));
124 $this->assertText(t('Machine-readable name field is required.'));
125 $this->assertText(t('Recipients field is required.'));
127 // Test validation of max_length machine name.
128 $recipients = ['simpletest&@example.com', 'simpletest2@example.com', 'simpletest3@example.com'];
129 $max_length = EntityTypeInterface::BUNDLE_MAX_LENGTH;
130 $max_length_exceeded = $max_length + 1;
131 $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length_exceeded)), $label = $this->randomMachineName($max_length_exceeded), implode(',', [$recipients[0]]), '', TRUE);
132 $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]));
133 $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length)), $label = $this->randomMachineName($max_length), implode(',', [$recipients[0]]), '', TRUE);
134 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
136 // Verify that the creation message contains a link to a contact form.
137 $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'contact/']);
138 $this->assert(isset($view_link), 'The message area contains a link to a contact form.');
140 // Create first valid form.
141 $this->addContactForm($id = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0]]), '', TRUE);
142 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
144 // Verify that the creation message contains a link to a contact form.
145 $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'contact/']);
146 $this->assert(isset($view_link), 'The message area contains a link to a contact form.');
148 // Check that the form was created in site default language.
149 $langcode = $this->config('contact.form.' . $id)->get('langcode');
150 $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
151 $this->assertEqual($langcode, $default_langcode);
153 // Make sure the newly created form is included in the list of forms.
154 $this->assertNoUniqueText($label, 'New form included in forms list.');
156 // Ensure that the recipient email is escaped on the listing.
157 $this->drupalGet('admin/structure/contact');
158 $this->assertEscaped($recipients[0]);
160 // Test update contact form.
161 $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');
162 $config = $this->config('contact.form.' . $id)->get();
163 $this->assertEqual($config['label'], $label);
164 $this->assertEqual($config['recipients'], [$recipients[0], $recipients[1]]);
165 $this->assertEqual($config['reply'], $reply);
166 $this->assertNotEqual($id, $this->config('contact.settings')->get('default_form'));
167 $this->assertText(t('Contact form @label has been updated.', ['@label' => $label]));
168 // Ensure the label is displayed on the contact page for this form.
169 $this->drupalGet('contact/' . $id);
170 $this->assertText($label);
172 // Reset the form back to be the default form.
173 $this->config('contact.settings')->set('default_form', $id)->save();
175 // Ensure that the contact form is shown without a form selection input.
176 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
177 $this->drupalLogout();
178 $this->drupalGet('contact');
179 $this->assertText(t('Your email address'));
180 $this->assertNoText(t('Form'));
181 $this->drupalLogin($admin_user);
184 $this->addContactForm(Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0], $recipients[1]]), '', FALSE);
185 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
187 $this->addContactForm($name = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0], $recipients[1], $recipients[2]]), '', FALSE);
188 $this->assertText(t('Contact form @label has been added.', ['@label' => $label]));
190 // Try adding a form that already exists.
191 $this->addContactForm($name, $label, '', '', FALSE);
192 $this->assertNoText(t('Contact form @label has been added.', ['@label' => $label]));
193 $this->assertRaw(t('The machine-readable name is already in use. It must be unique.'));
195 $this->drupalLogout();
197 // Check to see that anonymous user cannot see contact page without permission.
198 user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
199 $this->drupalGet('contact');
200 $this->assertResponse(403);
202 // Give anonymous user permission and see that page is viewable.
203 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
204 $this->drupalGet('contact');
205 $this->assertResponse(200);
207 // Submit contact form with invalid values.
208 $this->submitContact('', $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
209 $this->assertText(t('Your name field is required.'));
211 $this->submitContact($this->randomMachineName(16), '', $this->randomMachineName(16), $id, $this->randomMachineName(64));
212 $this->assertText(t('Your email address field is required.'));
214 $this->submitContact($this->randomMachineName(16), $invalid_recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
215 $this->assertRaw(t('The email address %mail is not valid.', ['%mail' => 'invalid']));
217 $this->submitContact($this->randomMachineName(16), $recipients[0], '', $id, $this->randomMachineName(64));
218 $this->assertText(t('Subject field is required.'));
220 $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, '');
221 $this->assertText(t('Message field is required.'));
223 // Test contact form with no default form selected.
224 $this->config('contact.settings')
225 ->set('default_form', '')
227 $this->drupalGet('contact');
228 $this->assertResponse(404);
230 // Try to access contact form with non-existing form IDs.
231 $this->drupalGet('contact/0');
232 $this->assertResponse(404);
233 $this->drupalGet('contact/' . $this->randomMachineName());
234 $this->assertResponse(404);
236 // Submit contact form with correct values and check flood interval.
237 for ($i = 0; $i < $flood_limit; $i++) {
238 $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
239 $this->assertText(t('Your message has been sent.'));
241 // Submit contact form one over limit.
242 $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
243 $this->assertRaw(t('You cannot send more than %number messages in 10 min. Try again later.', ['%number' => $this->config('contact.settings')->get('flood.limit')]));
245 // Test listing controller.
246 $this->drupalLogin($admin_user);
248 $this->deleteContactForms();
250 $label = $this->randomMachineName(16);
251 $recipients = implode(',', [$recipients[0], $recipients[1], $recipients[2]]);
252 $contact_form = Unicode::strtolower($this->randomMachineName(16));
253 $this->addContactForm($contact_form, $label, $recipients, '', FALSE);
254 $this->drupalGet('admin/structure/contact');
255 $this->clickLink(t('Edit'));
256 $this->assertResponse(200);
257 $this->assertFieldByName('label', $label);
259 // Test field UI and field integration.
260 $this->drupalGet('admin/structure/contact');
262 $view_link = $this->xpath('//table/tbody/tr/td/a[contains(@href, :href) and text()=:text]', [
263 ':href' => \Drupal::url('entity.contact_form.canonical', ['contact_form' => $contact_form]),
267 $this->assertTrue(!empty($view_link), 'Contact listing links to contact form.');
269 // Find out in which row the form we want to add a field to is.
270 foreach ($this->xpath('//table/tbody/tr') as $row) {
271 if ($row->findLink($label)) {
272 $row->clickLink('Manage fields');
277 $this->assertResponse(200);
278 $this->clickLink(t('Add field'));
279 $this->assertResponse(200);
281 // Create a simple textfield.
282 $field_name = Unicode::strtolower($this->randomMachineName());
283 $field_label = $this->randomMachineName();
284 $this->fieldUIAddNewField(NULL, $field_name, $field_label, 'text');
285 $field_name = 'field_' . $field_name;
287 // Check preview field can be ordered.
288 $this->drupalGet('admin/structure/contact/manage/' . $contact_form . '/form-display');
289 $this->assertText(t('Preview'));
291 // Check that the field is displayed.
292 $this->drupalGet('contact/' . $contact_form);
293 $this->assertText($field_label);
295 // Submit the contact form and verify the content.
297 'subject[0][value]' => $this->randomMachineName(),
298 'message[0][value]' => $this->randomMachineName(),
299 $field_name . '[0][value]' => $this->randomMachineName(),
301 $this->drupalPostForm(NULL, $edit, t('Send message'));
302 $mails = $this->getMails();
303 $mail = array_pop($mails);
304 $this->assertEqual($mail['subject'], t('[@label] @subject', ['@label' => $label, '@subject' => $edit['subject[0][value]']]));
305 $this->assertTrue(strpos($mail['body'], $field_label));
306 $this->assertTrue(strpos($mail['body'], $edit[$field_name . '[0][value]']));
308 // Test messages and redirect.
309 /** @var \Drupal\contact\ContactFormInterface $form */
310 $form = ContactForm::load($contact_form);
311 $form->setMessage('Thanks for your submission.');
312 $form->setRedirectPath('/user/' . $admin_user->id());
314 // Check that the field is displayed.
315 $this->drupalGet('contact/' . $contact_form);
317 // Submit the contact form and verify the content.
319 'subject[0][value]' => $this->randomMachineName(),
320 'message[0][value]' => $this->randomMachineName(),
321 $field_name . '[0][value]' => $this->randomMachineName(),
323 $this->drupalPostForm(NULL, $edit, t('Send message'));
324 $this->assertText('Thanks for your submission.');
325 $this->assertUrl('user/' . $admin_user->id());
327 // Test Empty message.
328 /** @var \Drupal\contact\ContactFormInterface $form */
329 $form = ContactForm::load($contact_form);
330 $form->setMessage('');
331 $form->setRedirectPath('/user/' . $admin_user->id());
333 $this->drupalGet('admin/structure/contact/manage/' . $contact_form);
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 $result = $this->xpath('//div[@role=:role]', [':role' => 'contentinfo']);
345 $this->assertEqual(count($result), 0, 'Messages not found.');
346 $this->assertUrl('user/' . $admin_user->id());
348 // Test preview and visibility of the message field and label. Submit the
349 // contact form and verify the content.
351 'subject[0][value]' => $this->randomMachineName(),
352 'message[0][value]' => $this->randomMachineName(),
353 $field_name . '[0][value]' => $this->randomMachineName(),
355 $this->drupalPostForm($form->toUrl('canonical'), $edit, t('Preview'));
357 // Message is now by default displayed twice, once for the form element and
358 // once for the viewed message.
359 $page_text = $this->getSession()->getPage()->getText();
360 $this->assertGreaterThan(1, substr_count($page_text, t('Message')));
361 $this->assertSession()->responseContains('class="field field--name-message field--type-string-long field--label-above');
362 $this->assertSession()->pageTextContains($edit['message[0][value]']);
364 // Hide the message field label.
366 'fields[message][label]' => 'hidden',
368 $this->drupalPostForm('admin/structure/contact/manage/' . $contact_form . '/display', $display_edit, t('Save'));
370 $this->drupalPostForm($form->toUrl('canonical'), $edit, t('Preview'));
371 // Message should only be displayed once now.
372 $page_text = $this->getSession()->getPage()->getText();
373 $this->assertEquals(1, substr_count($page_text, t('Message')));
374 $this->assertSession()->responseContains('class="field field--name-message field--type-string-long field--label-hidden field__item">');
375 $this->assertSession()->pageTextContains($edit['message[0][value]']);
379 * Tests auto-reply on the site-wide contact form.
381 public function testAutoReply() {
382 // Create and log in administrative user.
383 $admin_user = $this->drupalCreateUser([
384 'access site-wide contact form',
385 'administer contact forms',
386 'administer permissions',
388 'access site reports'
390 $this->drupalLogin($admin_user);
392 // Set up three forms, 2 with an auto-reply and one without.
393 $foo_autoreply = $this->randomMachineName(40);
394 $bar_autoreply = $this->randomMachineName(40);
395 $this->addContactForm('foo', 'foo', 'foo@example.com', $foo_autoreply, FALSE);
396 $this->addContactForm('bar', 'bar', 'bar@example.com', $bar_autoreply, FALSE);
397 $this->addContactForm('no_autoreply', 'no_autoreply', 'bar@example.com', '', FALSE);
399 // Log the current user out in order to test the name and email fields.
400 $this->drupalLogout();
401 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
403 // Test the auto-reply for form 'foo'.
404 $email = $this->randomMachineName(32) . '@example.com';
405 $subject = $this->randomMachineName(64);
406 $this->submitContact($this->randomMachineName(16), $email, $subject, 'foo', $this->randomString(128));
408 // We are testing the auto-reply, so there should be one email going to the sender.
409 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
410 $this->assertEqual(count($captured_emails), 1);
411 $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($foo_autoreply)));
413 // Test the auto-reply for form 'bar'.
414 $email = $this->randomMachineName(32) . '@example.com';
415 $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'bar', $this->randomString(128));
417 // Auto-reply for form 'bar' should result in one auto-reply email to the sender.
418 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
419 $this->assertEqual(count($captured_emails), 1);
420 $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($bar_autoreply)));
422 // Verify that no auto-reply is sent when the auto-reply field is left blank.
423 $email = $this->randomMachineName(32) . '@example.com';
424 $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'no_autoreply', $this->randomString(128));
425 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
426 $this->assertEqual(count($captured_emails), 0);
428 // Verify that the current error message doesn't show, that the auto-reply
429 // doesn't get sent and the correct silent error gets logged.
431 entity_get_form_display('contact_message', 'foo', 'default')
432 ->removeComponent('mail')
434 $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'foo', $this->randomString(128));
435 $this->assertNoText('Unable to send email. Contact the site administrator if the problem persists.');
436 $captured_emails = $this->getMails(['id' => 'contact_page_autoreply', 'to' => $email]);
437 $this->assertEqual(count($captured_emails), 0);
438 $this->drupalLogin($admin_user);
439 $this->drupalGet('admin/reports/dblog');
440 $this->assertRaw('Error sending auto-reply, missing sender e-mail address in foo');
447 * The form machine name.
448 * @param string $label
450 * @param string $recipients
451 * The list of recipient email addresses.
452 * @param string $reply
453 * The auto-reply text that is sent to a user upon completing the contact
455 * @param bool $selected
456 * A Boolean indicating whether the form should be selected by default.
457 * @param string $message
458 * The message that will be displayed to a user upon completing the contact
460 * @param array $third_party_settings
461 * Array of third party settings to be added to the posted form data.
463 public function addContactForm($id, $label, $recipients, $reply, $selected, $message = 'Your message has been sent.', $third_party_settings = []) {
465 $edit['label'] = $label;
467 $edit['message'] = $message;
468 $edit['recipients'] = $recipients;
469 $edit['reply'] = $reply;
470 $edit['selected'] = ($selected ? TRUE : FALSE);
471 $edit += $third_party_settings;
472 $this->drupalPostForm('admin/structure/contact/add', $edit, t('Save'));
479 * The form machine name.
480 * @param string $label
482 * @param string $recipients
483 * The list of recipient email addresses.
484 * @param string $reply
485 * The auto-reply text that is sent to a user upon completing the contact
487 * @param bool $selected
488 * A Boolean indicating whether the form should be selected by default.
489 * @param string $message
490 * The message that will be displayed to a user upon completing the contact
492 * @param string $redirect
493 * The path where user will be redirect after this form has been submitted..
495 public function updateContactForm($id, $label, $recipients, $reply, $selected, $message = 'Your message has been sent.', $redirect = '/') {
497 $edit['label'] = $label;
498 $edit['recipients'] = $recipients;
499 $edit['reply'] = $reply;
500 $edit['selected'] = ($selected ? TRUE : FALSE);
501 $edit['message'] = $message;
502 $edit['redirect'] = $redirect;
503 $this->drupalPostForm("admin/structure/contact/manage/$id", $edit, t('Save'));
507 * Submits the contact form.
509 * @param string $name
510 * The name of the sender.
511 * @param string $mail
512 * The email address of the sender.
513 * @param string $subject
514 * The subject of the message.
516 * The form ID of the message.
517 * @param string $message
520 public function submitContact($name, $mail, $subject, $id, $message) {
522 $edit['name'] = $name;
523 $edit['mail'] = $mail;
524 $edit['subject[0][value]'] = $subject;
525 $edit['message[0][value]'] = $message;
526 if ($id == $this->config('contact.settings')->get('default_form')) {
527 $this->drupalPostForm('contact', $edit, t('Send message'));
530 $this->drupalPostForm('contact/' . $id, $edit, t('Send message'));
537 public function deleteContactForms() {
538 $contact_forms = ContactForm::loadMultiple();;
539 foreach ($contact_forms as $id => $contact_form) {
540 if ($id == 'personal') {
541 // Personal form could not be deleted.
542 $this->drupalGet("admin/structure/contact/manage/$id/delete");
543 $this->assertResponse(403);
546 $this->drupalPostForm("admin/structure/contact/manage/$id/delete", [], t('Delete'));
547 $this->assertRaw(t('The contact form %label has been deleted.', ['%label' => $contact_form->label()]));
548 $this->assertFalse(ContactForm::load($id), format_string('Form %contact_form not found', ['%contact_form' => $contact_form->label()]));