first commit

This commit is contained in:
2024-07-15 12:33:27 +02:00
commit ce50ae282b
22084 changed files with 2623791 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
name: 'Contact test views'
type: module
description: 'Provides default views for views contact tests.'
package: Testing
dependencies:
- contact_storage:contact_storage
- drupal:language
# Information added by Drupal.org packaging script on 2024-06-22
version: '8.x-1.3+5-dev'
project: 'contact_storage'
datestamp: 1719055400

View File

@@ -0,0 +1,187 @@
langcode: en
status: true
dependencies:
module:
- contact
- contact_storage
id: test_contact_message_bulk_form
label: ''
module: views
description: ''
tag: ''
base_table: contact_message
base_field: id
display:
default:
display_plugin: default
id: default
display_title: Master
position: null
display_options:
style:
type: table
row:
type: fields
fields:
message_bulk_form:
id: message_bulk_form
table: contact_message
field: message_bulk_form
relationship: none
group_type: group
admin_label: ''
label: 'Message operations bulk form'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
action_title: 'With selection'
include_exclude: exclude
selected_actions: { }
entity_type: contact_message
plugin_id: message_bulk_form
subject:
table: contact_message
field: subject
id: subject
entity_type: null
entity_field: subject
plugin_id: field
relationship: none
group_type: group
admin_label: ''
label: Subject
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: string
settings: { }
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
filters: { }
sorts:
id:
id: id
table: contact_message
field: id
relationship: none
group_type: group
admin_label: ''
order: ASC
exposed: false
expose:
label: ''
entity_type: contact_message
entity_field: id
plugin_id: standard
title: ''
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: 0
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
tags: { }
page_1:
display_plugin: page
id: page_1
display_title: Page
position: 1
display_options:
display_extenders: { }
path: test-contact-message-bulk-form
cache_metadata:
max-age: 0
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
tags: { }

View File

@@ -0,0 +1,83 @@
<?php
namespace Drupal\Tests\contact_storage\Functional;
use Drupal\Core\Session\AccountInterface;
use Drupal\views\Tests\ViewTestData;
/**
* Tests a contact message bulk form.
*
* @group contact_storage
* @see \Drupal\contact_storage\Plugin\views\field\MessageBulkForm
*/
class BulkFormTest extends ContactStorageTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Modules to be enabled.
*
* @var array
*/
protected static $modules = [
'contact_storage',
'contact_test_views',
'language',
];
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_contact_message_bulk_form'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::Setup();
// Create and login administrative user.
$admin_user = $this->drupalCreateUser([
'administer contact forms',
]);
$this->drupalLogin($admin_user);
// Create first valid contact form.
$mail = 'simpletest@example.com';
$this->addContactForm('test_id', 'test_label', $mail, TRUE);
$this->assertSession()->pageTextContains('Contact form test_label has been added.');
$this->drupalLogout();
// Ensure that anonymous can submit site-wide contact form.
user_role_grant_permissions(AccountInterface::ANONYMOUS_ROLE, ['access site-wide contact form']);
$this->drupalGet('contact');
$this->assertSession()->pageTextContains('Your email address');
// Submit contact form few times.
for ($i = 1; $i <= 5; $i++) {
$this->submitContact($this->randomMachineName(), $mail, $this->randomMachineName(), 'test_id', $this->randomMachineName());
$this->assertSession()->pageTextContains('Your message has been sent.');
}
}
/**
* Test multiple deletion.
*/
public function testBulkDeletion() {
$this->drupalGet('contact');
ViewTestData::createTestViews(get_class($this), ['contact_test_views']);
// Check the operations are accessible to the administer permission user.
$this->drupalLogin($this->drupalCreateUser(['administer contact forms']));
$this->drupalGet('test-contact-message-bulk-form');
// There are 2 options: "- Select -", "Delete contact message".
$elements = $this->xpath('//select[@id="edit-action"]//option[@value="contact_message_delete_action"]');
$this->assertSame(count($elements), 1, 'All contact message operations are found.');
$this->drupalGet('test-contact-message-bulk-form');
$this->submitForm([], 'Apply to selected items');
$this->assertSession()->pageTextContains('No message selected.');
}
}

View File

@@ -0,0 +1,133 @@
<?php
namespace Drupal\Tests\contact_storage\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Test\AssertMailTrait;
use Drupal\Tests\BrowserTestBase;
/**
* Tests personal contact form functionality.
*
* @group contact
*/
class ContactStoragePersonalTest extends BrowserTestBase {
use AssertMailTrait {
getMails as drupalGetMails;
}
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['contact', 'contact_storage', 'dblog'];
/**
* A user with some administrative permissions.
*
* @var \Drupal\user\UserInterface
*/
private $adminUser;
/**
* A user with permission to view profiles and access user contact forms.
*
* @var \Drupal\user\UserInterface
*/
private $webUser;
/**
* A user without any permissions.
*
* @var \Drupal\user\UserInterface
*/
private $contactUser;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
protected function setUp(): void {
parent::setUp();
// Create an admin user.
$this->adminUser = $this->drupalCreateUser(['administer contact forms', 'administer users', 'administer account settings', 'access site reports']);
// Create some normal users with their contact forms enabled by default.
$this->config('contact.settings')->set('user_default_enabled', TRUE)->save();
$this->webUser = $this->drupalCreateUser(['access user profiles', 'access user contact forms']);
$this->contactUser = $this->drupalCreateUser();
}
/**
* Tests that mails for contact messages are correctly sent.
*/
public function testSendPersonalContactMessage() {
// Ensure that the web user's email needs escaping.
$mail = $this->webUser->getAccountName() . '&escaped@example.com';
$this->webUser->setEmail($mail)->save();
$this->drupalLogin($this->webUser);
$this->drupalGet('user/' . $this->contactUser->id() . '/contact');
$this->assertSession()->assertEscaped($mail);
$message = $this->submitPersonalContact($this->contactUser);
$mails = $this->drupalGetMails();
$this->assertEquals(1, count($mails));
$mail = $mails[0];
$this->assertEquals($mail['to'], $this->contactUser->getEmail());
$this->assertEquals($mail['from'], $this->config('system.site')->get('mail'));
$this->assertEquals($mail['reply-to'], $this->webUser->getEmail());
$this->assertEquals($mail['key'], 'user_mail');
$variables = [
'@site-name' => $this->config('system.site')->get('name'),
'@subject' => $message['subject[0][value]'],
'@recipient-name' => $this->contactUser->getDisplayName(),
];
$subject = PlainTextOutput::renderFromHtml(t('[@site-name] @subject', $variables));
$this->assertEquals($mail['subject'], $subject, 'Subject is in sent message.');
$this->assertTrue(strpos($mail['body'], 'Hello ' . $variables['@recipient-name']) !== FALSE, 'Recipient name is in sent message.');
$this->assertTrue(strpos($mail['body'], $this->webUser->getDisplayName()) !== FALSE, 'Sender name is in sent message.');
$this->assertTrue(strpos($mail['body'], $message['message[0][value]']) !== FALSE, 'Message body is in sent message.');
// Check there was no problems raised during sending.
$this->drupalLogout();
$this->drupalLogin($this->adminUser);
// Verify that the correct watchdog message has been logged.
$this->drupalGet('/admin/reports/dblog');
$placeholders = [
'@sender_name' => $this->webUser->getAccountName(),
'@sender_email' => $this->webUser->getEmail(),
'@recipient_name' => $this->contactUser->getAccountName(),
];
$this->assertSession()->responseContains(new FormattableMarkup('@sender_name (@sender_email) sent @recipient_name an email.', $placeholders));
// Ensure an unescaped version of the email does not exist anywhere.
$this->assertSession()->responseNotContains($this->webUser->getEmail());
}
/**
* Fills out a user's personal contact form and submits it.
*
* @param \Drupal\Core\Session\AccountInterface $account
* A user object of the user being contacted.
* @param array $message
* (optional) An array with the form fields being used. Defaults to an empty
* array.
*
* @return array
* An array with the form fields being used.
*/
protected function submitPersonalContact(AccountInterface $account, array $message = []) {
$message += [
'subject[0][value]' => $this->randomMachineName(16),
'message[0][value]' => $this->randomMachineName(64),
];
$this->drupalGet('user/' . $account->id() . '/contact');
$this->submitForm($message, 'Send message');
return $message;
}
}

View File

@@ -0,0 +1,519 @@
<?php
namespace Drupal\Tests\contact_storage\Functional;
use Drupal\contact\Entity\ContactForm;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Test\AssertMailTrait;
use Drupal\Tests\field_ui\Traits\FieldUiTestTrait;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\filter\Entity\FilterFormat;
use Drupal\Tests\Traits\Core\PathAliasTestTrait;
/**
* Tests storing contact messages and viewing them through UI.
*
* @group contact_storage
*/
class ContactStorageTest extends ContactStorageTestBase {
use FieldUiTestTrait;
use AssertMailTrait {
getMails as drupalGetMails;
}
use PathAliasTestTrait;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* An administrative user with permission to administer contact forms.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'text',
'block',
'contact',
'language',
'field_ui',
'contact_test',
'contact_storage',
'filter',
];
protected function setUp(): void {
parent::setUp();
$this->drupalPlaceBlock('system_breadcrumb_block');
$this->drupalPlaceBlock('local_actions_block');
$this->drupalPlaceBlock('page_title_block');
$full_html_format = FilterFormat::create([
'format' => 'full_html',
'name' => 'Full HTML',
]);
$full_html_format->save();
// Create and login administrative user.
$this->adminUser = $this->drupalCreateUser([
'access site-wide contact form',
'administer contact forms',
'administer users',
'administer account settings',
'administer contact_message fields',
'administer contact_message form display',
'administer contact_message display',
'use text format full_html',
]);
$this->drupalLogin($this->adminUser);
}
/**
* Tests contact messages submitted through contact form.
*/
public function testContactStorage() {
// Create first valid contact form.
$mail = 'simpletest@example.com';
$this->addContactForm('test_id', 'test_label', $mail, TRUE);
$this->assertSession()->pageTextContains('Contact form test_label has been added.');
// Ensure that new contact form can be cloned.
$this->cloneContactForm('test_id', 'test_id_cloned');
$original_form = ContactForm::load('test_id');
$cloned_form = ContactForm::load('test_id_cloned');
$this->assertNotEquals($original_form->uuid(), $cloned_form->uuid());
// Ensure that anonymous can submit site-wide contact form.
user_role_grant_permissions(AccountInterface::ANONYMOUS_ROLE, ['access site-wide contact form']);
$this->drupalLogout();
$this->drupalGet('contact');
$this->assertSession()->pageTextContains('Your email address');
$this->assertSession()->pageTextNotContains('Form');
$this->submitContact('Test_name', $mail, 'Test_subject', 'test_id', 'Test_message');
$this->assertSession()->pageTextContains('Your message has been sent.');
// Verify that only 1 message has been sent (by default, the "Send a copy
// to yourself" option is disabled.
$captured_emails = $this->drupalGetMails();
$this->assertTrue(count($captured_emails) === 1);
// Login as admin.
$this->drupalLogin($this->adminUser);
// Verify that the global setting stating whether e-mails should be sent in
// HTML format is false by default.
$this->assertFalse(\Drupal::config('contact_storage.settings')->get('send_html'));
// Verify that this first e-mail was sent in plain text format.
$captured_emails = $this->drupalGetMails();
$this->assertTrue(strpos($captured_emails[0]['headers']['Content-Type'], 'text/plain') !== FALSE);
// Go to the settings form and enable sending messages in HTML format.
$this->drupalGet('/admin/structure/contact/settings');
$enable_html = [
'send_html' => TRUE,
];
$this->submitForm($enable_html, 'Save configuration');
// Check that the form POST was successful.
$this->assertSession()->pageTextContains('The configuration options have been saved.');
// Check that the global setting is properly updated.
$this->assertTrue(\Drupal::config('contact_storage.settings')->get('send_html'));
$display_fields = [
"The sender's name",
"The sender's email",
"Subject",
];
// Check that the page title is correct.
$this->drupalGet('contact/test_id');
$this->assertTrue(!empty($this->cssSelect('h1:contains(test_label)')));
$this->assertSession()->titleEquals('test_label | Drupal');
// Check that the configuration edit page title is correct.
$this->drupalGet('admin/structure/contact/manage/test_id');
$this->assertTrue(!empty($this->cssSelect('h1:contains(test_label)')));
$this->assertSession()->titleEquals('Edit test_label | Drupal');
// Check that name, subject and mail are configurable on display.
$this->drupalGet('admin/structure/contact/manage/test_id/display');
foreach ($display_fields as $label) {
$this->assertSession()->pageTextContains($label);
}
// Check that preview is configurable on form display.
$this->drupalGet('admin/structure/contact/manage/test_id/form-display');
$this->assertSession()->pageTextContains('Preview');
// Check the message list overview.
$this->drupalGet('admin/structure/contact/messages');
$rows = $this->xpath('//tbody/tr');
// Make sure only 1 message is available.
$this->assertEquals(count($rows), 1);
// Some fields should be present.
$this->assertSession()->pageTextContains('Test_subject');
$this->assertSession()->pageTextContains('Test_name');
$this->assertSession()->pageTextContains('test_label');
// Click the view link and make sure name, subject and email are displayed
// by default.
$this->clickLink('View');
foreach ($display_fields as $label) {
$this->assertSession()->pageTextContains($label);
}
// Make sure the stored message is correct.
$this->drupalGet('admin/structure/contact/messages');
$this->clickLink('Edit');
$this->assertSession()->fieldValueEquals('edit-name', 'Test_name');
$this->assertSession()->fieldValueEquals('edit-mail', $mail);
$this->assertSession()->fieldValueEquals('edit-subject-0-value', 'Test_subject');
$this->assertSession()->fieldValueEquals('edit-message-0-value', 'Test_message');
// Submit should redirect back to listing.
$this->submitForm([], 'Save');
$this->assertSession()->addressEquals('admin/structure/contact/messages');
// Delete the message.
$this->clickLink('Delete');
$this->submitForm([], 'Delete');
$this->assertSession()->responseContains((string) t('The @entity-type %label has been deleted.', [
// See \Drupal\Core\Entity\EntityDeleteFormTrait::getDeletionMessage().
'@entity-type' => 'contact message',
'%label' => 'Test_subject',
]));
// Make sure no messages are available.
$this->assertSession()->pageTextContains('There is no Contact message yet.');
// Fill the "Submit button text" field and assert the form can still be
// submitted.
$edit = [
'contact_storage_submit_text' => 'Submit the form',
'contact_storage_preview' => FALSE,
];
$this->drupalGet('admin/structure/contact/manage/test_id');
$this->submitForm($edit, 'Save');
$edit = [
'subject[0][value]' => 'Test subject',
'message[0][value]' => 'Test message',
];
$this->drupalGet('contact');
$element = $this->cssSelect('#edit-preview');
// Preview button is hidden.
$this->assertTrue(empty($element));
$this->submitForm($edit, 'Submit the form');
$this->assertSession()->pageTextContains('Your message has been sent.');
// Add an Options email item field to the form.
// There is a problem with allowed value. I was not able to create field
// manually on D10.
$settings = ['settings[allowed_values]' => "test_key1|test_label1|simpletest1@example.com\ntest_key2|test_label2|simpletest2@example.com"];
$this->fieldUIAddNewField('admin/structure/contact/manage/test_id', 'category', 'Category', 'contact_storage_options_email', $settings);
// Verify that the new field shows up correctly on the form.
$this->drupalGet('contact');
$this->assertSession()->pageTextContains('Category');
$this->assertSession()->optionExists('edit-field-category', '_none');
$this->assertSession()->optionExists('edit-field-category', 'test_key1');
$this->assertSession()->optionExists('edit-field-category', 'test_key2');
// Send a message using the Options email item field and enable the "Send a
// copy to yourself" option.
$captured_emails = $this->drupalGetMails();
$emails_count_before = count($captured_emails);
$edit = [
'subject[0][value]' => 'Test subject',
'message[0][value]' => 'Test message',
'field_category' => 'test_key2',
'copy' => 'checked',
];
$this->submitForm($edit, 'Submit the form');
$this->assertSession()->pageTextContains('Your message has been sent.');
// Check that 2 messages were sent and that the body of the last
// message contains the added message.
$captured_emails = $this->drupalGetMails();
$emails_count_after = count($captured_emails);
$this->assertTrue($emails_count_after === ($emails_count_before + 2));
$this->assertMailString('body', 'test_key2', 2);
// The last message is the one sent as a copy, the one before it is the
// original. Check that the original contains the added recipients and that
// the copied one is only sent to the sender.
$logged_in_user_email = $this->loggedInUser->getEmail();
$this->assertTrue($captured_emails[$emails_count_after - 2]['to'] == "$mail,simpletest2@example.com");
$this->assertTrue($captured_emails[$emails_count_after - 1]['to'] == $logged_in_user_email);
// Test clone functionality - add field to existing form.
$this->fieldUIAddNewField('admin/structure/contact/manage/test_id', 'text_field', 'Text field', 'text');
// Then clone it.
$this->cloneContactForm('test_id', 'test_id_2');
$edit = [
'subject[0][value]' => 'Test subject',
'message[0][value]' => 'Test message',
];
// The added field should be on the cloned form too.
$edit['field_text_field[0][value]'] = 'Some text';
$this->drupalGet('contact/test_id_2');
$this->submitForm($edit, 'Submit the form');
$form = ContactForm::load('test_id_2');
$this->assertNotEmpty($form->uuid());
// Try changing the options email label, field default value and setting it
// to required.
$this->drupalGet('/admin/structure/contact/manage/test_id/fields');
$this->clickLink('Edit');
$this->submitForm([
'label' => 'Category-2',
'required' => TRUE,
'default_value_input[field_category]' => 'test_key1',
], 'Save settings');
// Verify that the changes are visible into the contact form.
$this->drupalGet('contact');
$this->assertSession()->pageTextContains('Category-2');
$this->assertSession()->optionExists('edit-field-category', 'test_key1');
$this->assertSession()->optionExists('edit-field-category', 'test_key2');
$this->assertNotEmpty($this->xpath('//select[@id="edit-field-category" and @required="required"]//option[@value="test_key1"]'));
// Verify that the 'View messages' link exists for the 2 forms and that it
// links to the correct view.
$this->drupalGet('/admin/structure/contact');
$this->assertSession()->linkByHrefExists('/admin/structure/contact/messages?form=test_id');
$this->assertSession()->linkByHrefExists('/admin/structure/contact/messages?form=test_id_2');
// Create a new contact form and assert that the disable link exists for
// each forms.
$this->addContactForm('test_disable_id', 'test_disable_label', 'simpletest@example.com', FALSE);
$this->drupalGet('/admin/structure/contact');
$contact_form_count = count(ContactForm::loadMultiple());
// In D10 stark theme there are no li.disable, li.enable elements.
$this->assertEquals($contact_form_count, count($this->cssSelect('li a[href*="/disable"]:contains(Disable)')));
$this->drupalGet('/admin/structure/contact/manage/test_disable_id/disable');
// Disable the form and assert that there is 1 less "Disable" button and 1
// "Enable" button.
$this->submitForm([], 'Disable');
$this->assertSession()->pageTextContains('Disabled contact form test_disable_label.');
$this->drupalGet('/admin/structure/contact');
$this->assertEquals(($contact_form_count - 1), count($this->cssSelect('li a[href*="/disable"]:contains(Disable)')));
$this->assertEquals(1, count($this->cssSelect('li a[href*="/enable"]:contains(Enable)')));
// Assert that the disabled form has no input or text area and the message.
$this->drupalGet('contact/test_disable_id');
$this->assertEquals(0, count($this->cssSelect('input')));
$this->assertEquals(0, count($this->cssSelect('textarea')));
$this->assertSession()->pageTextContains('This contact form has been disabled.');
$this->drupalGet('/admin/structure/contact/manage/test_disable_id/enable');
// Try to re-enable the form and assert that it can be accessed.
$this->submitForm([], 'Enable');
$this->assertSession()->pageTextContains('Enabled contact form test_disable_label.');
$this->drupalGet('contact/test_disable_id');
$this->assertSession()->pageTextNotContains('This contact form has been disabled.');
// Create a new contact form with a custom disabled message, disable it and
// assert that the message displayed is correct.
$this->addContactForm('test_disable_id_2', 'test_disable_label_2', 'simpletest@example.com', FALSE, ['contact_storage_disabled_form_message' => 'custom disabled message']);
$this->drupalGet('/admin/structure/contact/manage/test_disable_id_2/disable');
$this->submitForm([], 'Disable');
$this->assertSession()->pageTextContains('Disabled contact form test_disable_label_2.');
$this->drupalGet('contact/test_disable_id_2');
$this->assertSession()->pageTextContains('custom disabled message');
}
/**
* Tests the url alias creation feature.
*/
public function testUrlAlias() {
// Add a second language to make sure aliases work with any language.
$language = ConfigurableLanguage::createFromLangcode('de');
$language->save();
// Set the second language as default.
$this->config('system.site')->set('default_langcode', $language->getId())->save();
$this->rebuildContainer();
$mail = 'simpletest@example.com';
// Test for alias without slash.
$this->addContactForm('form_alias_1', 'contactForm', $mail, FALSE, ['contact_storage_url_alias' => 'form51']);
$this->assertSession()->pageTextContains('The alias path has to start with a slash.');
$this->drupalGet('form51');
$this->assertSession()->statusCodeEquals(404);
// Test for correct alias. Verify that we land on the correct contact form.
$this->addContactForm('form_alias_2', 'contactForm', $mail, FALSE, ['contact_storage_url_alias' => '/form51']);
$this->assertSession()->pageTextContains('Contact form contactForm has been added.');
$this->drupalGet('form51');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('contactForm');
$this->assertSession()->buttonExists('Send message');
$this->drupalGet('admin/structure/contact/manage/form_alias_2');
// Edit the contact form without changing anything. Verify that the existing
// alias continues to work.
$this->submitForm([], 'Save');
$this->assertSession()->pageTextContains('Contact form contactForm has been updated.');
$this->drupalGet('form51');
$this->assertSession()->statusCodeEquals(200);
$this->drupalGet('admin/structure/contact/manage/form_alias_2');
// Edit the contact form by changing the alias. Verify that the new alias
// is generated and the old one removed.
$this->submitForm(['contact_storage_url_alias' => '/form52'], 'Save');
$this->assertSession()->pageTextContains('Contact form contactForm has been updated.');
$this->drupalGet('form51');
$this->assertSession()->statusCodeEquals(404);
$this->drupalGet('form52');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('contactForm');
$this->drupalGet('admin/structure/contact/manage/form_alias_2');
// Edit the contact form by removing the alias. Verify that is is deleted.
$this->submitForm(['contact_storage_url_alias' => ''], 'Save');
$this->assertSession()->pageTextContains('Contact form contactForm has been updated.');
$this->drupalGet('form52');
$this->assertSession()->statusCodeEquals(404);
$this->drupalGet('admin/structure/contact/manage/form_alias_2');
// Add an alias back and delete the contact form. Verify that the alias is
// deleted along with the contact form.
$this->submitForm(['contact_storage_url_alias' => '/form52'], 'Save');
$this->assertSession()->pageTextContains('Contact form contactForm has been updated.');
$this->drupalGet('form52');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('contactForm');
$this->drupalGet('admin/structure/contact/manage/form_alias_2/delete');
$this->submitForm([], 'Delete');
$alias = $this->loadPathAliasByConditions([
'path' => '/contact/form_alias_2',
]);
$this->assertNull($alias);
}
public function testMaximumSubmissionLimit() {
// Create a new contact form with a maximum submission limit of 2.
$this->addContactForm('test_id_3', 'test_label', 'simpletest@example.com', FALSE, ['contact_storage_maximum_submissions_user' => 2]);
$this->assertSession()->pageTextContains('Contact form test_label has been added.');
// Sends 2 messages with "Send yourself a copy" option activated, shouldn't
// reach the limit even if 2 messages are sent twice.
$this->drupalGet('contact/test_id_3');
$edit = [
'subject[0][value]' => 'Test subject',
'message[0][value]' => 'Test message',
'copy' => 'checked',
];
$this->submitForm($edit, 'Send message');
$this->assertSession()->pageTextContains('Your message has been sent.');
$this->drupalGet('contact/test_id_3');
$this->submitForm($edit, 'Send message');
$this->assertSession()->pageTextContains('Your message has been sent.');
// Try accessing the form after the limit has been reached.
$this->drupalGet('contact/test_id_3');
$this->assertSession()->pageTextContains('You have reached the maximum submission limit of 2 for this form.');
}
/**
* Tests the Auto-reply field.
*/
public function testAutoReplyField() {
// Create a new contact form with an auto-reply.
$this->addContactForm('test_auto_reply_id_1', 'test_auto_reply_label_1', 'simpletest@example.com', TRUE, ['reply[value]' => "auto_reply_1\nsecond_line"]);
$this->assertSession()->pageTextContains('Contact form test_auto_reply_label_1 has been added.');
// Verify that the auto-reply shows up in the field and only offers
// one format (plain text), since html e-mails are disabled.
$this->drupalGet('admin/structure/contact/manage/test_auto_reply_id_1');
$this->assertNotEmpty($this->xpath('//textarea[@id="edit-reply-value" and text()=:text]', [':text' => "auto_reply_1\nsecond_line"]));
$this->assertEmpty($this->xpath('//select[@name="reply[format]"]'));
$this->drupalGet('contact');
$edit = [
'subject[0][value]' => 'Test subject',
'message[0][value]' => 'Test message',
];
$this->drupalGet('contact');
$this->submitForm($edit, 'Send message');
$this->assertSession()->pageTextContains('Your message has been sent.');
$captured_emails = $this->drupalGetMails();
// Checks that the last captured email is the auto-reply, has a correct
// body and is in html format.
$this->assertEquals(end($captured_emails)['key'], 'page_autoreply');
$this->assertStringContainsString("auto_reply_1\nsecond_line", end($captured_emails)['body']);
$this->assertStringContainsString('text/plain', end($captured_emails)['headers']['Content-Type']);
$this->drupalGet('/admin/structure/contact/settings');
// Enable sending messages in html format and verify that the available
// formats correctly show up on the contact form edit page.
$this->submitForm(['send_html' => TRUE], 'Save configuration');
$this->drupalGet('admin/structure/contact/manage/test_auto_reply_id_1');
$this->assertNotEmpty($this->xpath('//select[@name="reply[format]"]//option[@value="plain_text" and @selected="selected"]'));
$this->assertNotEmpty($this->xpath('//select[@name="reply[format]"]//option[@value="full_html"]'));
// Use custom testing mail system to support HTML mails.
$mail_config = $this->config('system.mail');
$mail_config->set('interface.default', 'test_contact_storage_html_mail');
$mail_config->save();
// Test sending a HTML mail.
$this->drupalGet('contact');
$edit = [
'subject[0][value]' => 'Test subject',
'message[0][value]' => 'Test message',
];
$this->drupalGet('contact');
$this->submitForm($edit, 'Send message');
$this->assertSession()->pageTextContains('Your message has been sent.');
$captured_emails = $this->drupalGetMails();
$this->assertEquals('page_autoreply', end($captured_emails)['key']);
// 10.1 - "auto_reply_1<br />\nsecond_line"
// 10.2 - "auto_reply_1<br>\nsecond_line"
$body = end($captured_emails)['body'];
$this->assertTrue(strpos($body, "auto_reply_1<br") !== FALSE);
$this->assertTrue(strpos($body, ">\nsecond_line") !== FALSE);
$this->assertEquals(end($captured_emails)['headers']['Content-Type'], 'text/html');
$this->drupalGet('admin/structure/contact/manage/test_auto_reply_id_1');
// Select full html format (not selected by default) and verify that it is
// properly set.
$this->submitForm(['reply[format]' => 'full_html'], 'Save');
$this->drupalGet('admin/structure/contact/manage/test_auto_reply_id_1');
$this->assertNotEmpty($this->xpath('//select[@name="reply[format]"]//option[@value="full_html" and @selected="selected"]'));
}
/**
* Clone form.
*
* @param string $original_form_id
* The original form machine name.
* @param string $clone_form_id
* The new form machine name.
*/
protected function cloneContactForm($original_form_id, $clone_form_id) {
$this->drupalGet("admin/structure/contact/manage/$original_form_id/clone");
$this->submitForm([
'id' => $clone_form_id,
'label' => 'Cloned',
], 'Clone');
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Drupal\Tests\contact_storage\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Defines a base-class for contact-storage tests.
*/
abstract class ContactStorageTestBase extends BrowserTestBase {
/**
* Adds a form.
*
* @param string $id
* The form machine name.
* @param string $label
* The form label.
* @param string $recipients
* The list of recipient email addresses.
* @param bool $selected
* A Boolean indicating whether the form should be selected by default.
* @param array $third_party_settings
* Array of third party settings to be added to the posted form data.
* @param string $message
* The message that will be displayed to a user upon completing the contact
* form.
*/
public function addContactForm($id, $label, $recipients, $selected, $third_party_settings = [], $message = 'Your message has been sent.') {
$this->drupalGet('admin/structure/contact/add');
$edit = [];
$edit['label'] = $label;
$edit['id'] = $id;
// 8.2.x added the message field, which is by default empty. Conditionally
// submit it if the field can be found.
$xpath = '//textarea[@name=:value]|//input[@name=:value]|//select[@name=:value]';
if ($this->xpath($this->assertSession()->buildXPathQuery($xpath, [':value' => 'message']))) {
$edit['message'] = $message;
}
$edit['recipients'] = $recipients;
$edit['selected'] = ($selected ? TRUE : FALSE);
$edit += $third_party_settings;
$this->submitForm($edit, 'Save');
}
/**
* Submits the contact form.
*
* @param string $name
* The name of the sender.
* @param string $mail
* The email address of the sender.
* @param string $subject
* The subject of the message.
* @param string $id
* The form ID of the message.
* @param string $message
* The message body.
*/
public function submitContact($name, $mail, $subject, $id, $message) {
$edit = [];
$edit['name'] = $name;
$edit['mail'] = $mail;
$edit['subject[0][value]'] = $subject;
$edit['message[0][value]'] = $message;
if ($id == $this->config('contact.settings')->get('default_form')) {
$this->drupalGet('contact');
$this->submitForm($edit, 'Send message');
}
else {
$this->drupalGet('contact/' . $id);
$this->submitForm($edit, 'Send message');
}
}
}

View File

@@ -0,0 +1,142 @@
<?php
namespace Drupal\Tests\contact_storage\Functional;
/**
* Tests adding contact form as entity reference and viewing them through UI.
*
* @group contact_storage
*/
class ContactViewBuilderTest extends ContactStorageTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'user',
'node',
'contact',
'field_ui',
'contact_test',
'contact_storage',
];
/**
* An administrative user with permission to administer contact forms.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create Article node type.
$this->drupalCreateContentType([
'type' => 'article',
'name' => 'Article',
'display_submitted' => FALSE,
]);
}
/**
* Tests contact view builder functionality.
*/
public function testContactViewBuilder() {
// Create test admin user.
$this->adminUser = $this->drupalCreateUser([
'administer content types',
'access site-wide contact form',
'administer contact forms',
'administer users',
'administer account settings',
'administer contact_message fields',
'create article content',
]);
// Login as admin user.
$this->drupalLogin($this->adminUser);
// Create first valid contact form.
$mail = 'simpletest@example.com';
$this->addContactForm('test_id', 'test_label', $mail, TRUE);
$this->assertSession()->pageTextContains('Contact form test_label has been added.');
$field_name = 'contact';
$entity_type = 'node';
$bundle_name = 'article';
// Add a Entity Reference Contact Field to Article content type.
$field_storage = \Drupal::entityTypeManager()
->getStorage('field_storage_config')
->create([
'field_name' => $field_name,
'entity_type' => $entity_type,
'type' => 'entity_reference',
'settings' => ['target_type' => 'contact_form'],
]);
$field_storage->save();
$field = \Drupal::entityTypeManager()
->getStorage('field_config')
->create([
'field_storage' => $field_storage,
'bundle' => $bundle_name,
'settings' => [
'handler' => 'default',
],
]);
$field->save();
// Configure the contact reference field form Entity form display.
$this->container->get('entity_display.repository')->getFormDisplay($entity_type, $bundle_name)
->setComponent($field_name, [
'type' => 'options_select',
'settings' => [
'weight' => 20,
],
])
->save();
// Configure the contact reference field form Entity view display.
$this->container->get('entity_display.repository')->getViewDisplay('node', 'article')
->setComponent($field_name, [
'label' => 'above',
'type' => 'entity_reference_entity_view',
'weight' => 20,
])
->save();
// Display Article creation form.
$this->drupalGet('node/add/article');
$title_key = 'title[0][value]';
$body_key = 'body[0][value]';
$contact_key = 'contact';
// Create article node.
$edit = [];
$edit[$title_key] = $this->randomMachineName(8);
$edit[$body_key] = $this->randomMachineName(16);
$edit[$contact_key] = 'test_id';
$this->drupalGet('node/add/article');
$this->submitForm($edit, 'Save');
// Check that the node exists in the database.
$node = $this->drupalGetNodeByTitle($edit[$title_key]);
$this->drupalGet('node/' . $node->id());
// Some fields should be present.
$this->assertSession()->pageTextContains('Your email address');
$this->assertSession()->pageTextContains('Subject');
$this->assertSession()->pageTextContains('Message');
$this->assertSession()->fieldExists('subject[0][value]');
$this->assertSession()->fieldExists('message[0][value]');
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Drupal\Tests\contact_storage\Kernel;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests contact_storage ID field.
*
* @group contact_storage
*/
class ContactStorageFieldTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['contact', 'user', 'system'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('contact_message');
}
/**
* Covers contact_storage_mode_preinstall().
*/
public function testContactIdFieldIsCreated() {
$this->container->get('module_installer')->install(['contact_storage']);
// There should be no updates as contact_storage_module_pre_install() should
// have applied the new field.
$this->assertTrue(empty($this->container->get('entity.definition_update_manager')->needsUpdates()['contact_message']));
$this->assertTrue(!empty($this->container->get('entity_field.manager')->getFieldStorageDefinitions('contact_message')['id']));
}
}