ContactPersonalTest.php 12.4 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\contact\Tests\ContactPersonalTest.
6 7 8 9
 */

namespace Drupal\contact\Tests;

10
use Drupal\Component\Utility\String;
11
use Drupal\Core\Session\AccountInterface;
12 13 14
use Drupal\simpletest\WebTestBase;

/**
15 16 17
 * Tests personal contact form functionality.
 *
 * @group contact
18 19
 */
class ContactPersonalTest extends WebTestBase {
20 21 22 23 24 25

  /**
   * Modules to enable.
   *
   * @var array
   */
26
  public static $modules = array('contact', 'dblog');
27

28 29 30
  /**
   * A user with some administrative permissions.
   *
31
   * @var \Drupal\user\UserInterface
32
   */
33
  private $adminUser;
34 35

  /**
36
   * A user with permission to view profiles and access user contact forms.
37
   *
38
   * @var \Drupal\user\UserInterface
39
   */
40
  private $webUser;
41 42 43 44

  /**
   * A user without any permissions.
   *
45
   * @var \Drupal\user\UserInterface
46
   */
47
  private $contactUser;
48

49
  protected function setUp() {
50
    parent::setUp();
51 52

    // Create an admin user.
53
    $this->adminUser = $this->drupalCreateUser(array('administer contact forms', 'administer users', 'administer account settings', 'access site reports'));
54 55

    // Create some normal users with their contact forms enabled by default.
56
    $this->config('contact.settings')->set('user_default_enabled', TRUE)->save();
57
    $this->webUser = $this->drupalCreateUser(array('access user profiles', 'access user contact forms'));
58
    $this->contactUser = $this->drupalCreateUser();
59 60
  }

61 62 63 64
  /**
   * Tests that mails for contact messages are correctly sent.
   */
  function testSendPersonalContactMessage() {
65
    $this->drupalLogin($this->webUser);
66

67
    $message = $this->submitPersonalContact($this->contactUser);
68 69 70
    $mails = $this->drupalGetMails();
    $this->assertEqual(1, count($mails));
    $mail = $mails[0];
71
    $this->assertEqual($mail['to'], $this->contactUser->getEmail());
72
    $this->assertEqual($mail['from'], $this->config('system.site')->get('mail'));
73
    $this->assertEqual($mail['reply-to'], $this->webUser->getEmail());
74 75
    $this->assertEqual($mail['key'], 'user_mail');
    $variables = array(
76
      '!site-name' => $this->config('system.site')->get('name'),
77
      '!subject' => $message['subject[0][value]'],
78
      '!recipient-name' => $this->contactUser->getUsername(),
79 80 81
    );
    $this->assertEqual($mail['subject'], t('[!site-name] !subject', $variables), 'Subject is in sent message.');
    $this->assertTrue(strpos($mail['body'], t('Hello !recipient-name,', $variables)) !== FALSE, 'Recipient name is in sent message.');
82
    $this->assertTrue(strpos($mail['body'], $this->webUser->getUsername()) !== FALSE, 'Sender name is in sent message.');
83
    $this->assertTrue(strpos($mail['body'], $message['message[0][value]']) !== FALSE, 'Message body is in sent message.');
84 85 86

    // Check there was no problems raised during sending.
    $this->drupalLogout();
87
    $this->drupalLogin($this->adminUser);
88 89 90
    // Verify that the correct watchdog message has been logged.
    $this->drupalGet('/admin/reports/dblog');
    $placeholders = array(
91 92 93
      '@sender_name' => $this->webUser->username,
      '@sender_email' => $this->webUser->getEmail(),
      '@recipient_name' => $this->contactUser->getUsername()
94
    );
95
    $this->assertText(String::format('@sender_name (@sender_email) sent @recipient_name an email.', $placeholders));
96 97
  }

98 99 100 101
  /**
   * Tests access to the personal contact form.
   */
  function testPersonalContactAccess() {
102
    // Test allowed access to admin user's contact form.
103 104
    $this->drupalLogin($this->webUser);
    $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
105
    $this->assertResponse(200);
106
    // Check the page title is properly displayed.
107
    $this->assertRaw(t('Contact @username', array('@username' => $this->adminUser->getUsername())));
108 109 110

    // Test denied access to admin user's own contact form.
    $this->drupalLogout();
111 112
    $this->drupalLogin($this->adminUser);
    $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
113 114
    $this->assertResponse(403);

115
    // Test allowed access to user with contact form enabled.
116 117
    $this->drupalLogin($this->webUser);
    $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
118 119
    $this->assertResponse(200);

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    // Test that there is no access to personal contact forms for users
    // without an email address configured.
    $original_email = $this->contactUser->getEmail();
    $this->contactUser->setEmail(FALSE)->save();
    $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
    $this->assertResponse(404, 'Not found (404) returned when visiting a personal contact form for a user with no email address');

    // Test that the 'contact tab' does not appear on the user profiles
    // for users without an email address configured.
    $this->drupalGet('user/' . $this->contactUser->id());
    $contact_link = '/user/' . $this->contactUser->id() . '/contact';
    $this->assertResponse(200);
    $this->assertNoLinkByHref ($contact_link, 'The "contact" tab is hidden on profiles for users with no email address');

    // Restore original email address.
    $this->contactUser->setEmail($original_email)->save();

137
    // Test denied access to the user's own contact form.
138
    $this->drupalGet('user/' . $this->webUser->id() . '/contact');
139 140 141 142 143 144 145 146 147
    $this->assertResponse(403);

    // Test always denied access to the anonymous user contact form.
    $this->drupalGet('user/0/contact');
    $this->assertResponse(403);

    // Test that anonymous users can access the contact form.
    $this->drupalLogout();
    user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('access user contact forms'));
148
    $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
149 150
    $this->assertResponse(200);

151
    // Test that anonymous users can access admin user's contact form.
152
    $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
153 154
    $this->assertResponse(200);

155 156
    // Revoke the personal contact permission for the anonymous user.
    user_role_revoke_permissions(DRUPAL_ANONYMOUS_RID, array('access user contact forms'));
157
    $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
158
    $this->assertResponse(403);
159
    $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
160
    $this->assertResponse(403);
161 162

    // Disable the personal contact form.
163
    $this->drupalLogin($this->adminUser);
164
    $edit = array('contact_default_status' => FALSE);
165
    $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
166
    $this->assertText(t('The configuration options have been saved.'), 'Setting successfully saved.');
167 168 169 170
    $this->drupalLogout();

    // Re-create our contacted user with personal contact forms disabled by
    // default.
171
    $this->contactUser = $this->drupalCreateUser();
172 173

    // Test denied access to a user with contact form disabled.
174 175
    $this->drupalLogin($this->webUser);
    $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
176 177 178
    $this->assertResponse(403);

    // Test allowed access for admin user to a user with contact form disabled.
179 180
    $this->drupalLogin($this->adminUser);
    $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
181 182 183
    $this->assertResponse(200);

    // Re-create our contacted user as a blocked user.
184 185 186
    $this->contactUser = $this->drupalCreateUser();
    $this->contactUser->block();
    $this->contactUser->save();
187 188

    // Test that blocked users can still be contacted by admin.
189
    $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
190 191 192
    $this->assertResponse(200);

    // Test that blocked users cannot be contacted by non-admins.
193 194
    $this->drupalLogin($this->webUser);
    $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
195
    $this->assertResponse(403);
196 197 198

    // Test enabling and disabling the contact page through the user profile
    // form.
199
    $this->drupalGet('user/' . $this->webUser->id() . '/edit');
200
    $this->assertNoFieldChecked('edit-contact--2');
201
    $this->assertFalse(\Drupal::service('user.data')->get('contact', $this->webUser->id(), 'enabled'), 'Personal contact form disabled');
202
    $this->drupalPostForm(NULL, array('contact' => TRUE), t('Save'));
203
    $this->assertFieldChecked('edit-contact--2');
204
    $this->assertTrue(\Drupal::service('user.data')->get('contact', $this->webUser->id(), 'enabled'), 'Personal contact form enabled');
205 206 207

    // Test with disabled global default contact form in combination with a user
    // that has the contact form enabled.
208
    $this->config('contact.settings')->set('user_default_enabled', FALSE)->save();
209 210 211 212 213
    $this->contactUser = $this->drupalCreateUser();
    \Drupal::service('user.data')->set('contact', $this->contactUser->id(), 'enabled', 1);

    $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
    $this->assertResponse(200);
214 215 216 217 218 219 220
  }

  /**
   * Tests the personal contact form flood protection.
   */
  function testPersonalContactFlood() {
    $flood_limit = 3;
221
    $this->config('contact.settings')->set('flood.limit', $flood_limit)->save();
222 223 224 225 226 227

    // Clear flood table in preparation for flood test and allow other checks to complete.
    db_delete('flood')->execute();
    $num_records_flood = db_query("SELECT COUNT(*) FROM {flood}")->fetchField();
    $this->assertIdentical($num_records_flood, '0', 'Flood table emptied.');

228
    $this->drupalLogin($this->webUser);
229 230 231

    // Submit contact form with correct values and check flood interval.
    for ($i = 0; $i < $flood_limit; $i++) {
232
      $this->submitPersonalContact($this->contactUser);
233 234 235 236
      $this->assertText(t('Your message has been sent.'), 'Message sent.');
    }

    // Submit contact form one over limit.
237
    $this->drupalGet('user/' . $this->contactUser->id(). '/contact');
238
    $this->assertRaw(t('You cannot send more than %number messages in @interval. Try again later.', array('%number' => $flood_limit, '@interval' => \Drupal::service('date.formatter')->formatInterval($this->config('contact.settings')->get('flood.interval')))), 'Normal user denied access to flooded contact form.');
239 240 241

    // Test that the admin user can still access the contact form even though
    // the flood limit was reached.
242
    $this->drupalLogin($this->adminUser);
243 244 245
    $this->assertNoText('Try again later.', 'Admin user not denied access to flooded contact form.');
  }

246 247 248 249 250 251 252
  /**
   * Tests the personal contact form based access when an admin adds users.
   */
  function testAdminContact() {
    user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('access user contact forms'));
    $this->checkContactAccess(200);
    $this->checkContactAccess(403, FALSE);
253
    $config = $this->config('contact.settings');
254 255 256 257 258 259 260 261 262 263 264 265 266 267
    $config->set('user_default_enabled', FALSE);
    $config->save();
    $this->checkContactAccess(403);
  }

  /**
   * Creates a user and then checks contact form access.
   *
   * @param integer $response
   *   The expected response code.
   * @param boolean $contact_value
   *   (optional) The value the contact field should be set too.
   */
  protected function checkContactAccess($response, $contact_value = NULL) {
268
    $this->drupalLogin($this->adminUser);
269
    $this->drupalGet('admin/people/create');
270
    if ($this->config('contact.settings')->get('user_default_enabled', TRUE)) {
271 272 273 274 275
      $this->assertFieldChecked('edit-contact--2');
    }
    else {
      $this->assertNoFieldChecked('edit-contact--2');
    }
276
    $name = $this->randomMachineName();
277 278
    $edit = array(
      'name' => $name,
279
      'mail' => $this->randomMachineName() . '@example.com',
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
      'pass[pass1]' => $pass = $this->randomString(),
      'pass[pass2]' => $pass,
      'notify' => FALSE,
    );
    if (isset($contact_value)) {
      $edit['contact'] = $contact_value;
    }
    $this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
    $user = user_load_by_name($name);
    $this->drupalLogout();

    $this->drupalGet('user/' . $user->id() . '/contact');
    $this->assertResponse($response);
  }

295 296 297
  /**
   * Fills out a user's personal contact form and submits it.
   *
298
   * @param \Drupal\Core\Session\AccountInterface $account
299
   *   A user object of the user being contacted.
300
   * @param array $message
301 302
   *   (optional) An array with the form fields being used. Defaults to an empty
   *   array.
303 304 305
   *
   * @return array
   *   An array with the form fields being used.
306
   */
307
  protected function submitPersonalContact(AccountInterface $account, array $message = array()) {
308
    $message += array(
309 310
      'subject[0][value]' => $this->randomMachineName(16),
      'message[0][value]' => $this->randomMachineName(64),
311
    );
312
    $this->drupalPostForm('user/' . $account->id() . '/contact', $message, t('Send message'));
313
    return $message;
314
  }
315

316
}