Backup of db before drupal security update
[yaffs-website] / web / core / modules / contact / tests / src / Functional / ContactPersonalTest.php
1 <?php
2
3 namespace Drupal\Tests\contact\Functional;
4
5 use Drupal\Component\Utility\SafeMarkup;
6 use Drupal\Component\Render\PlainTextOutput;
7 use Drupal\Core\Session\AccountInterface;
8 use Drupal\Core\Test\AssertMailTrait;
9 use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
10 use Drupal\Tests\BrowserTestBase;
11 use Drupal\user\RoleInterface;
12
13 /**
14  * Tests personal contact form functionality.
15  *
16  * @group contact
17  */
18 class ContactPersonalTest extends BrowserTestBase {
19
20   use AssertMailTrait;
21   use AssertPageCacheContextsAndTagsTrait;
22
23   /**
24    * Modules to enable.
25    *
26    * @var array
27    */
28   public static $modules = ['contact', 'dblog'];
29
30   /**
31    * A user with some administrative permissions.
32    *
33    * @var \Drupal\user\UserInterface
34    */
35   private $adminUser;
36
37   /**
38    * A user with permission to view profiles and access user contact forms.
39    *
40    * @var \Drupal\user\UserInterface
41    */
42   private $webUser;
43
44   /**
45    * A user without any permissions.
46    *
47    * @var \Drupal\user\UserInterface
48    */
49   private $contactUser;
50
51   protected function setUp() {
52     parent::setUp();
53
54     // Create an admin user.
55     $this->adminUser = $this->drupalCreateUser(['administer contact forms', 'administer users', 'administer account settings', 'access site reports']);
56
57     // Create some normal users with their contact forms enabled by default.
58     $this->config('contact.settings')->set('user_default_enabled', TRUE)->save();
59     $this->webUser = $this->drupalCreateUser(['access user profiles', 'access user contact forms']);
60     $this->contactUser = $this->drupalCreateUser();
61   }
62
63   /**
64    * Tests that mails for contact messages are correctly sent.
65    */
66   public function testSendPersonalContactMessage() {
67     // Ensure that the web user's email needs escaping.
68     $mail = $this->webUser->getUsername() . '&escaped@example.com';
69     $this->webUser->setEmail($mail)->save();
70     $this->drupalLogin($this->webUser);
71
72     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
73     $this->assertEscaped($mail);
74     $message = $this->submitPersonalContact($this->contactUser);
75     $mails = $this->getMails();
76     $this->assertEqual(1, count($mails));
77     $mail = $mails[0];
78     $this->assertEqual($mail['to'], $this->contactUser->getEmail());
79     $this->assertEqual($mail['from'], $this->config('system.site')->get('mail'));
80     $this->assertEqual($mail['reply-to'], $this->webUser->getEmail());
81     $this->assertEqual($mail['key'], 'user_mail');
82     $variables = [
83       '@site-name' => $this->config('system.site')->get('name'),
84       '@subject' => $message['subject[0][value]'],
85       '@recipient-name' => $this->contactUser->getDisplayName(),
86     ];
87     $subject = PlainTextOutput::renderFromHtml(t('[@site-name] @subject', $variables));
88     $this->assertEqual($mail['subject'], $subject, 'Subject is in sent message.');
89     $this->assertTrue(strpos($mail['body'], 'Hello ' . $variables['@recipient-name']) !== FALSE, 'Recipient name is in sent message.');
90     $this->assertTrue(strpos($mail['body'], $this->webUser->getDisplayName()) !== FALSE, 'Sender name is in sent message.');
91     $this->assertTrue(strpos($mail['body'], $message['message[0][value]']) !== FALSE, 'Message body is in sent message.');
92
93     // Check there was no problems raised during sending.
94     $this->drupalLogout();
95     $this->drupalLogin($this->adminUser);
96     // Verify that the correct watchdog message has been logged.
97     $this->drupalGet('/admin/reports/dblog');
98     $placeholders = [
99       '@sender_name' => $this->webUser->username,
100       '@sender_email' => $this->webUser->getEmail(),
101       '@recipient_name' => $this->contactUser->getUsername()
102     ];
103     $this->assertRaw(SafeMarkup::format('@sender_name (@sender_email) sent @recipient_name an email.', $placeholders));
104     // Ensure an unescaped version of the email does not exist anywhere.
105     $this->assertNoRaw($this->webUser->getEmail());
106   }
107
108   /**
109    * Tests access to the personal contact form.
110    */
111   public function testPersonalContactAccess() {
112     // Test allowed access to admin user's contact form.
113     $this->drupalLogin($this->webUser);
114     $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
115     $this->assertResponse(200);
116     // Check the page title is properly displayed.
117     $this->assertRaw(t('Contact @username', ['@username' => $this->adminUser->getDisplayName()]));
118
119     // Test denied access to admin user's own contact form.
120     $this->drupalLogout();
121     $this->drupalLogin($this->adminUser);
122     $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
123     $this->assertResponse(403);
124
125     // Test allowed access to user with contact form enabled.
126     $this->drupalLogin($this->webUser);
127     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
128     $this->assertResponse(200);
129
130     // Test that there is no access to personal contact forms for users
131     // without an email address configured.
132     $original_email = $this->contactUser->getEmail();
133     $this->contactUser->setEmail(FALSE)->save();
134     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
135     $this->assertResponse(404, 'Not found (404) returned when visiting a personal contact form for a user with no email address');
136
137     // Test that the 'contact tab' does not appear on the user profiles
138     // for users without an email address configured.
139     $this->drupalGet('user/' . $this->contactUser->id());
140     $contact_link = '/user/' . $this->contactUser->id() . '/contact';
141     $this->assertResponse(200);
142     $this->assertNoLinkByHref ($contact_link, 'The "contact" tab is hidden on profiles for users with no email address');
143
144     // Restore original email address.
145     $this->contactUser->setEmail($original_email)->save();
146
147     // Test denied access to the user's own contact form.
148     $this->drupalGet('user/' . $this->webUser->id() . '/contact');
149     $this->assertResponse(403);
150
151     // Test always denied access to the anonymous user contact form.
152     $this->drupalGet('user/0/contact');
153     $this->assertResponse(403);
154
155     // Test that anonymous users can access the contact form.
156     $this->drupalLogout();
157     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access user contact forms']);
158     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
159     $this->assertResponse(200);
160
161     // Test that anonymous users can access admin user's contact form.
162     $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
163     $this->assertResponse(200);
164     $this->assertCacheContext('user');
165
166     // Revoke the personal contact permission for the anonymous user.
167     user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access user contact forms']);
168     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
169     $this->assertResponse(403);
170     $this->assertCacheContext('user');
171     $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
172     $this->assertResponse(403);
173
174     // Disable the personal contact form.
175     $this->drupalLogin($this->adminUser);
176     $edit = ['contact_default_status' => FALSE];
177     $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
178     $this->assertText(t('The configuration options have been saved.'), 'Setting successfully saved.');
179     $this->drupalLogout();
180
181     // Re-create our contacted user with personal contact forms disabled by
182     // default.
183     $this->contactUser = $this->drupalCreateUser();
184
185     // Test denied access to a user with contact form disabled.
186     $this->drupalLogin($this->webUser);
187     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
188     $this->assertResponse(403);
189
190     // Test allowed access for admin user to a user with contact form disabled.
191     $this->drupalLogin($this->adminUser);
192     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
193     $this->assertResponse(200);
194
195     // Re-create our contacted user as a blocked user.
196     $this->contactUser = $this->drupalCreateUser();
197     $this->contactUser->block();
198     $this->contactUser->save();
199
200     // Test that blocked users can still be contacted by admin.
201     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
202     $this->assertResponse(200);
203
204     // Test that blocked users cannot be contacted by non-admins.
205     $this->drupalLogin($this->webUser);
206     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
207     $this->assertResponse(403);
208
209     // Test enabling and disabling the contact page through the user profile
210     // form.
211     $this->drupalGet('user/' . $this->webUser->id() . '/edit');
212     $this->assertNoFieldChecked('edit-contact--2');
213     $this->assertFalse(\Drupal::service('user.data')->get('contact', $this->webUser->id(), 'enabled'), 'Personal contact form disabled');
214     $this->drupalPostForm(NULL, ['contact' => TRUE], t('Save'));
215     $this->assertFieldChecked('edit-contact--2');
216     $this->assertTrue(\Drupal::service('user.data')->get('contact', $this->webUser->id(), 'enabled'), 'Personal contact form enabled');
217
218     // Test with disabled global default contact form in combination with a user
219     // that has the contact form enabled.
220     $this->config('contact.settings')->set('user_default_enabled', FALSE)->save();
221     $this->contactUser = $this->drupalCreateUser();
222     \Drupal::service('user.data')->set('contact', $this->contactUser->id(), 'enabled', 1);
223
224     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
225     $this->assertResponse(200);
226   }
227
228   /**
229    * Tests the personal contact form flood protection.
230    */
231   public function testPersonalContactFlood() {
232     $flood_limit = 3;
233     $this->config('contact.settings')->set('flood.limit', $flood_limit)->save();
234
235     $this->drupalLogin($this->webUser);
236
237     // Submit contact form with correct values and check flood interval.
238     for ($i = 0; $i < $flood_limit; $i++) {
239       $this->submitPersonalContact($this->contactUser);
240       $this->assertText(t('Your message has been sent.'), 'Message sent.');
241     }
242
243     // Submit contact form one over limit.
244     $this->submitPersonalContact($this->contactUser);
245     $this->assertRaw(t('You cannot send more than %number messages in @interval. Try again later.', ['%number' => $flood_limit, '@interval' => \Drupal::service('date.formatter')->formatInterval($this->config('contact.settings')->get('flood.interval'))]), 'Normal user denied access to flooded contact form.');
246
247     // Test that the admin user can still access the contact form even though
248     // the flood limit was reached.
249     $this->drupalLogin($this->adminUser);
250     $this->assertNoText('Try again later.', 'Admin user not denied access to flooded contact form.');
251   }
252
253   /**
254    * Tests the personal contact form based access when an admin adds users.
255    */
256   public function testAdminContact() {
257     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access user contact forms']);
258     $this->checkContactAccess(200);
259     $this->checkContactAccess(403, FALSE);
260     $config = $this->config('contact.settings');
261     $config->set('user_default_enabled', FALSE);
262     $config->save();
263     $this->checkContactAccess(403);
264   }
265
266   /**
267    * Creates a user and then checks contact form access.
268    *
269    * @param int $response
270    *   The expected response code.
271    * @param bool $contact_value
272    *   (optional) The value the contact field should be set too.
273    */
274   protected function checkContactAccess($response, $contact_value = NULL) {
275     $this->drupalLogin($this->adminUser);
276     $this->drupalGet('admin/people/create');
277     if ($this->config('contact.settings')->get('user_default_enabled', TRUE)) {
278       $this->assertFieldChecked('edit-contact--2');
279     }
280     else {
281       $this->assertNoFieldChecked('edit-contact--2');
282     }
283     $name = $this->randomMachineName();
284     $edit = [
285       'name' => $name,
286       'mail' => $this->randomMachineName() . '@example.com',
287       'pass[pass1]' => $pass = $this->randomString(),
288       'pass[pass2]' => $pass,
289       'notify' => FALSE,
290     ];
291     if (isset($contact_value)) {
292       $edit['contact'] = $contact_value;
293     }
294     $this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
295     $user = user_load_by_name($name);
296     $this->drupalLogout();
297
298     $this->drupalGet('user/' . $user->id() . '/contact');
299     $this->assertResponse($response);
300   }
301
302   /**
303    * Fills out a user's personal contact form and submits it.
304    *
305    * @param \Drupal\Core\Session\AccountInterface $account
306    *   A user object of the user being contacted.
307    * @param array $message
308    *   (optional) An array with the form fields being used. Defaults to an empty
309    *   array.
310    *
311    * @return array
312    *   An array with the form fields being used.
313    */
314   protected function submitPersonalContact(AccountInterface $account, array $message = []) {
315     $message += [
316       'subject[0][value]' => $this->randomMachineName(16),
317       'message[0][value]' => $this->randomMachineName(64),
318     ];
319     $this->drupalPostForm('user/' . $account->id() . '/contact', $message, t('Send message'));
320     return $message;
321   }
322
323 }