ContactSitewideTest.php 18.9 KB
Newer Older
1
<?php
2 3 4

namespace Drupal\contact\Tests;

5
use Drupal\Component\Utility\Unicode;
6
use Drupal\contact\Entity\ContactForm;
7
use Drupal\Core\Mail\MailFormatHelper;
8
use Drupal\field_ui\Tests\FieldUiTestTrait;
9
use Drupal\simpletest\WebTestBase;
10
use Drupal\Core\Entity\EntityTypeInterface;
11
use Drupal\user\RoleInterface;
12

13
/**
14 15
 * Tests site-wide contact form functionality.
 *
16 17
 * @see \Drupal\contact\Tests\ContactStorageTest
 *
18
 * @group contact
19
 */
20
class ContactSitewideTest extends WebTestBase {
21

22 23
  use FieldUiTestTrait;

24 25 26 27 28
  /**
   * Modules to enable.
   *
   * @var array
   */
29 30 31 32 33 34 35 36
  public static $modules = array('text', 'contact', 'field_ui', 'contact_test', 'block');

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->drupalPlaceBlock('system_breadcrumb_block');
37
    $this->drupalPlaceBlock('local_actions_block');
38
    $this->drupalPlaceBlock('page_title_block');
39
  }
40

41
  /**
42
   * Tests configuration options and the site-wide contact form.
43 44
   */
  function testSiteWideContact() {
45
    // Create and log in administrative user.
46 47 48 49
    $admin_user = $this->drupalCreateUser(array(
      'access site-wide contact form',
      'administer contact forms',
      'administer users',
50
      'administer account settings',
51 52
      'administer contact_message fields',
    ));
53
    $this->drupalLogin($admin_user);
54

55 56 57 58
    // Check the presence of expected cache tags.
    $this->drupalGet('contact');
    $this->assertCacheTag('config:contact.settings');

59
    $flood_limit = 3;
60
    $this->config('contact.settings')
61 62 63
      ->set('flood.limit', $flood_limit)
      ->set('flood.interval', 600)
      ->save();
64 65 66 67

    // Set settings.
    $edit = array();
    $edit['contact_default_status'] = TRUE;
68
    $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
69
    $this->assertText(t('The configuration options have been saved.'));
70

71
    $this->drupalGet('admin/structure/contact');
72
    // Default form exists.
73
    $this->assertLinkByHref('admin/structure/contact/manage/feedback/delete');
74
    // User form could not be changed or deleted.
75 76
    // Cannot use ::assertNoLinkByHref as it does partial url matching and with
    // field_ui enabled admin/structure/contact/manage/personal/fields exists.
77
    // @todo: See https://www.drupal.org/node/2031223 for the above.
78
    $edit_link = $this->xpath('//a[@href=:href]', array(
79
      ':href' => \Drupal::url('entity.contact_form.edit_form', array('contact_form' => 'personal'))
80
    ));
81
    $this->assertTrue(empty($edit_link), format_string('No link containing href %href found.',
82 83
      array('%href' => 'admin/structure/contact/manage/personal')
    ));
84 85 86 87 88
    $this->assertNoLinkByHref('admin/structure/contact/manage/personal/delete');

    $this->drupalGet('admin/structure/contact/manage/personal');
    $this->assertResponse(403);

89 90
    // Delete old forms to ensure that new forms are used.
    $this->deleteContactForms();
91
    $this->drupalGet('admin/structure/contact');
92
    $this->assertText('Personal', 'Personal form was not deleted');
93
    $this->assertNoLinkByHref('admin/structure/contact/manage/feedback');
94

95
    // Ensure that the contact form won't be shown without forms.
96
    user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form'));
97 98
    $this->drupalLogout();
    $this->drupalGet('contact');
99
    $this->assertResponse(404);
100

101
    $this->drupalLogin($admin_user);
102 103 104
    $this->drupalGet('contact');
    $this->assertResponse(200);
    $this->assertText(t('The contact form has not been configured.'));
105
    // Test access personal form via site-wide contact page.
106 107
    $this->drupalGet('contact/personal');
    $this->assertResponse(403);
108

109
    // Add forms.
110
    // Test invalid recipients.
111
    $invalid_recipients = array('invalid', 'invalid@', 'invalid@site.', '@site.', '@site.com');
112
    foreach ($invalid_recipients as $invalid_recipient) {
113
      $this->addContactForm($this->randomMachineName(16), $this->randomMachineName(16), $invalid_recipient, '', FALSE);
114
      $this->assertRaw(t('%recipient is an invalid email address.', array('%recipient' => $invalid_recipient)));
115 116
    }

117 118
    // Test validation of empty form and recipients fields.
    $this->addContactForm('', '', '', '', TRUE);
119 120 121
    $this->assertText(t('Label field is required.'));
    $this->assertText(t('Machine-readable name field is required.'));
    $this->assertText(t('Recipients field is required.'));
122

123
    // Test validation of max_length machine name.
124
    $recipients = array('simpletest&@example.com', 'simpletest2@example.com', 'simpletest3@example.com');
125 126
    $max_length = EntityTypeInterface::BUNDLE_MAX_LENGTH;
    $max_length_exceeded = $max_length + 1;
127
    $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length_exceeded)), $label = $this->randomMachineName($max_length_exceeded), implode(',', array($recipients[0])), '', TRUE);
128
    $this->assertText(format_string('Machine-readable name cannot be longer than @max characters but is currently @exceeded characters long.', array('@max' => $max_length, '@exceeded' => $max_length_exceeded)));
129
    $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length)), $label = $this->randomMachineName($max_length), implode(',', array($recipients[0])), '', TRUE);
130
    $this->assertRaw(t('Contact form %label has been added.', array('%label' => $label)));
131

132
    // Create first valid form.
133
    $this->addContactForm($id = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($recipients[0])), '', TRUE);
134
    $this->assertRaw(t('Contact form %label has been added.', array('%label' => $label)));
135

136
    // Check that the form was created in site default language.
137
    $langcode = $this->config('contact.form.' . $id)->get('langcode');
138
    $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
139 140
    $this->assertEqual($langcode, $default_langcode);

141 142
    // Make sure the newly created form is included in the list of forms.
    $this->assertNoUniqueText($label, 'New form included in forms list.');
143

144 145 146 147
    // Ensure that the recipient email is escaped on the listing.
    $this->drupalGet('admin/structure/contact');
    $this->assertEscaped($recipients[0]);

148 149
    // Test update contact form.
    $this->updateContactForm($id, $label = $this->randomMachineName(16), $recipients_str = implode(',', array($recipients[0], $recipients[1])), $reply = $this->randomMachineName(30), FALSE);
150
    $config = $this->config('contact.form.' . $id)->get();
151 152 153
    $this->assertEqual($config['label'], $label);
    $this->assertEqual($config['recipients'], array($recipients[0], $recipients[1]));
    $this->assertEqual($config['reply'], $reply);
154
    $this->assertNotEqual($id, $this->config('contact.settings')->get('default_form'));
155 156
    $this->assertRaw(t('Contact form %label has been updated.', array('%label' => $label)));
    // Ensure the label is displayed on the contact page for this form.
157 158
    $this->drupalGet('contact/' . $id);
    $this->assertText($label);
159

160
    // Reset the form back to be the default form.
161
    $this->config('contact.settings')->set('default_form', $id)->save();
162

163
    // Ensure that the contact form is shown without a form selection input.
164
    user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form'));
165 166
    $this->drupalLogout();
    $this->drupalGet('contact');
167
    $this->assertText(t('Your email address'));
168
    $this->assertNoText(t('Form'));
169 170
    $this->drupalLogin($admin_user);

171
    // Add more forms.
172
    $this->addContactForm(Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($recipients[0], $recipients[1])), '', FALSE);
173
    $this->assertRaw(t('Contact form %label has been added.', array('%label' => $label)));
174

175
    $this->addContactForm($name = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($recipients[0], $recipients[1], $recipients[2])), '', FALSE);
176
    $this->assertRaw(t('Contact form %label has been added.', array('%label' => $label)));
177

178 179 180
    // Try adding a form that already exists.
    $this->addContactForm($name, $label, '', '', FALSE);
    $this->assertNoRaw(t('Contact form %label has been added.', array('%label' => $label)));
181
    $this->assertRaw(t('The machine-readable name is already in use. It must be unique.'));
182

183 184
    $this->drupalLogout();

185
    // Check to see that anonymous user cannot see contact page without permission.
186
    user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form'));
187
    $this->drupalGet('contact');
188
    $this->assertResponse(403);
189 190

    // Give anonymous user permission and see that page is viewable.
191
    user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form'));
192
    $this->drupalGet('contact');
193
    $this->assertResponse(200);
194 195

    // Submit contact form with invalid values.
196
    $this->submitContact('', $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
197
    $this->assertText(t('Your name field is required.'));
198

199
    $this->submitContact($this->randomMachineName(16), '', $this->randomMachineName(16), $id, $this->randomMachineName(64));
200
    $this->assertText(t('Your email address field is required.'));
201

202
    $this->submitContact($this->randomMachineName(16), $invalid_recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
203
    $this->assertRaw(t('The email address %mail is not valid.', array('%mail' => 'invalid')));
204

205
    $this->submitContact($this->randomMachineName(16), $recipients[0], '', $id, $this->randomMachineName(64));
206
    $this->assertText(t('Subject field is required.'));
207

208
    $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, '');
209
    $this->assertText(t('Message field is required.'));
210

211
    // Test contact form with no default form selected.
212
    $this->config('contact.settings')
213
      ->set('default_form', '')
214
      ->save();
215
    $this->drupalGet('contact');
216
    $this->assertResponse(404);
217

218
    // Try to access contact form with non-existing form IDs.
219 220
    $this->drupalGet('contact/0');
    $this->assertResponse(404);
221
    $this->drupalGet('contact/' . $this->randomMachineName());
222
    $this->assertResponse(404);
223

224
    // Submit contact form with correct values and check flood interval.
225
    for ($i = 0; $i < $flood_limit; $i++) {
226
      $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
227
      $this->assertText(t('Your message has been sent.'));
228 229
    }
    // Submit contact form one over limit.
230
    $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
231
    $this->assertRaw(t('You cannot send more than %number messages in 10 min. Try again later.', array('%number' => $this->config('contact.settings')->get('flood.limit'))));
232 233 234 235

    // Test listing controller.
    $this->drupalLogin($admin_user);

236
    $this->deleteContactForms();
237

238
    $label = $this->randomMachineName(16);
239
    $recipients = implode(',', array($recipients[0], $recipients[1], $recipients[2]));
240
    $contact_form = Unicode::strtolower($this->randomMachineName(16));
241
    $this->addContactForm($contact_form, $label, $recipients, '', FALSE);
242 243 244 245
    $this->drupalGet('admin/structure/contact');
    $this->clickLink(t('Edit'));
    $this->assertResponse(200);
    $this->assertFieldByName('label', $label);
246 247 248 249

    // Test field UI and field integration.
    $this->drupalGet('admin/structure/contact');

250 251 252 253 254 255 256
    $view_link = $this->xpath('//table/tbody/tr/td/a[contains(@href, :href) and text()=:text]', [
      ':href' => \Drupal::url('entity.contact_form.canonical', ['contact_form' => $contact_form]),
      ':text' => $label,
      ]
    );
    $this->assertTrue(!empty($view_link), 'Contact listing links to contact form.');

257
    // Find out in which row the form we want to add a field to is.
258 259
    $i = 0;
    foreach($this->xpath('//table/tbody/tr') as $row) {
260
      if (((string) $row->td[0]->a) == $label) {
261 262 263 264 265 266 267
        break;
      }
      $i++;
    }

    $this->clickLink(t('Manage fields'), $i);
    $this->assertResponse(200);
268 269
    $this->clickLink(t('Add field'));
    $this->assertResponse(200);
270 271

    // Create a simple textfield.
272 273 274 275
    $field_name = Unicode::strtolower($this->randomMachineName());
    $field_label = $this->randomMachineName();
    $this->fieldUIAddNewField(NULL, $field_name, $field_label, 'text');
    $field_name = 'field_' . $field_name;
276 277

    // Check that the field is displayed.
278
    $this->drupalGet('contact/' . $contact_form);
279 280 281 282
    $this->assertText($field_label);

    // Submit the contact form and verify the content.
    $edit = array(
283 284 285
      'subject[0][value]' => $this->randomMachineName(),
      'message[0][value]' => $this->randomMachineName(),
      $field_name . '[0][value]' => $this->randomMachineName(),
286
    );
287
    $this->drupalPostForm(NULL, $edit, t('Send message'));
288 289
    $mails = $this->drupalGetMails();
    $mail = array_pop($mails);
290
    $this->assertEqual($mail['subject'], t('[@label] @subject', array('@label' => $label, '@subject' => $edit['subject[0][value]'])));
291
    $this->assertTrue(strpos($mail['body'], $field_label));
292
    $this->assertTrue(strpos($mail['body'], $edit[$field_name . '[0][value]']));
293 294
  }

295
  /**
296 297
   * Tests auto-reply on the site-wide contact form.
   */
298
  function testAutoReply() {
299
    // Create and log in administrative user.
300
    $admin_user = $this->drupalCreateUser(array('access site-wide contact form', 'administer contact forms', 'administer permissions', 'administer users'));
301 302
    $this->drupalLogin($admin_user);

303
    // Set up three forms, 2 with an auto-reply and one without.
304 305
    $foo_autoreply = $this->randomMachineName(40);
    $bar_autoreply = $this->randomMachineName(40);
306 307 308
    $this->addContactForm('foo', 'foo', 'foo@example.com', $foo_autoreply, FALSE);
    $this->addContactForm('bar', 'bar', 'bar@example.com', $bar_autoreply, FALSE);
    $this->addContactForm('no_autoreply', 'no_autoreply', 'bar@example.com', '', FALSE);
309

310
    // Log the current user out in order to test the name and email fields.
webchick's avatar
webchick committed
311
    $this->drupalLogout();
312
    user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form'));
webchick's avatar
webchick committed
313

314
    // Test the auto-reply for form 'foo'.
315 316 317
    $email = $this->randomMachineName(32) . '@example.com';
    $subject = $this->randomMachineName(64);
    $this->submitContact($this->randomMachineName(16), $email, $subject, 'foo', $this->randomString(128));
318

319
    // We are testing the auto-reply, so there should be one email going to the sender.
320
    $captured_emails = $this->drupalGetMails(array('id' => 'contact_page_autoreply', 'to' => $email));
321
    $this->assertEqual(count($captured_emails), 1);
322
    $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($foo_autoreply)));
323

324
    // Test the auto-reply for form 'bar'.
325 326
    $email = $this->randomMachineName(32) . '@example.com';
    $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'bar', $this->randomString(128));
327

328
    // Auto-reply for form 'bar' should result in one auto-reply email to the sender.
329
    $captured_emails = $this->drupalGetMails(array('id' => 'contact_page_autoreply', 'to' => $email));
330
    $this->assertEqual(count($captured_emails), 1);
331
    $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($bar_autoreply)));
332 333

    // Verify that no auto-reply is sent when the auto-reply field is left blank.
334 335
    $email = $this->randomMachineName(32) . '@example.com';
    $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'no_autoreply', $this->randomString(128));
336
    $captured_emails = $this->drupalGetMails(array('id' => 'contact_page_autoreply', 'to' => $email));
337
    $this->assertEqual(count($captured_emails), 0);
338 339
  }

340
  /**
341
   * Adds a form.
342
   *
343
   * @param string $id
344
   *   The form machine name.
345
   * @param string $label
346
   *   The form label.
347
   * @param string $recipients
348
   *   The list of recipient email addresses.
349 350 351
   * @param string $reply
   *   The auto-reply text that is sent to a user upon completing the contact
   *   form.
352
   * @param bool $selected
353
   *   A Boolean indicating whether the form should be selected by default.
354 355
   * @param array $third_party_settings
   *   Array of third party settings to be added to the posted form data.
356
   */
357
  function addContactForm($id, $label, $recipients, $reply, $selected, $third_party_settings = []) {
358
    $edit = array();
359 360
    $edit['label'] = $label;
    $edit['id'] = $id;
361 362
    $edit['recipients'] = $recipients;
    $edit['reply'] = $reply;
363
    $edit['selected'] = ($selected ? TRUE : FALSE);
364
    $edit += $third_party_settings;
365
    $this->drupalPostForm('admin/structure/contact/add', $edit, t('Save'));
366 367
  }

368
  /**
369
   * Updates a form.
370
   *
371
   * @param string $id
372
   *   The form machine name.
373
   * @param string $label
374
   *   The form label.
375
   * @param string $recipients
376
   *   The list of recipient email addresses.
377 378 379
   * @param string $reply
   *   The auto-reply text that is sent to a user upon completing the contact
   *   form.
380
   * @param bool $selected
381
   *   A Boolean indicating whether the form should be selected by default.
382
   */
383
  function updateContactForm($id, $label, $recipients, $reply, $selected) {
384
    $edit = array();
385
    $edit['label'] = $label;
386 387
    $edit['recipients'] = $recipients;
    $edit['reply'] = $reply;
388
    $edit['selected'] = ($selected ? TRUE : FALSE);
389
    $this->drupalPostForm("admin/structure/contact/manage/$id", $edit, t('Save'));
390 391
  }

392
  /**
393
   * Submits the contact form.
394
   *
395 396 397
   * @param string $name
   *   The name of the sender.
   * @param string $mail
398
   *   The email address of the sender.
399 400
   * @param string $subject
   *   The subject of the message.
401
   * @param string $id
402
   *   The form ID of the message.
403 404
   * @param string $message
   *   The message body.
405
   */
406
  function submitContact($name, $mail, $subject, $id, $message) {
407 408 409
    $edit = array();
    $edit['name'] = $name;
    $edit['mail'] = $mail;
410 411
    $edit['subject[0][value]'] = $subject;
    $edit['message[0][value]'] = $message;
412
    if ($id == $this->config('contact.settings')->get('default_form')) {
413
      $this->drupalPostForm('contact', $edit, t('Send message'));
414 415
    }
    else {
416
      $this->drupalPostForm('contact/' . $id, $edit, t('Send message'));
417
    }
418 419 420
  }

  /**
421
   * Deletes all forms.
422
   */
423
  function deleteContactForms() {
424
    $contact_forms = ContactForm::loadMultiple();;
425
    foreach ($contact_forms as $id => $contact_form) {
426
      if ($id == 'personal') {
427
        // Personal form could not be deleted.
428 429 430 431
        $this->drupalGet("admin/structure/contact/manage/$id/delete");
        $this->assertResponse(403);
      }
      else {
432
        $this->drupalPostForm("admin/structure/contact/manage/$id/delete", array(), t('Delete'));
433
        $this->assertRaw(t('The contact form %label has been deleted.', array('%label' => $contact_form->label())));
434
        $this->assertFalse(ContactForm::load($id), format_string('Form %contact_form not found', array('%contact_form' => $contact_form->label())));
435
      }
436 437 438 439
    }
  }

}