Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Ref] Extend email trait test, process more sanely #21553

Merged
merged 2 commits into from
Sep 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 62 additions & 26 deletions CRM/Contact/Form/Task/EmailTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ trait CRM_Contact_Form_Task_EmailTrait {
*/
public $_templates;

/**
* Email addresses to send to.
*
* @var array
*/
protected $emails = [];

/**
* Store "to" contact details.
* @var array
Expand Down Expand Up @@ -138,24 +145,6 @@ protected function preProcessFromAddress(): void {
// are having to re-write contactIds afterwards due to this inappropriate variable setting
// If we don't have any contact IDs, use the logged in contact ID
$form->_contactIds = $form->_contactIds ?: [CRM_Core_Session::getLoggedInContactID()];

$fromEmailValues = CRM_Core_BAO_Email::getFromEmail();

if (empty($fromEmailValues)) {
CRM_Core_Error::statusBounce(ts('Your user record does not have a valid email address and no from addresses have been configured.'));
}

$form->_emails = $fromEmailValues;
$defaults = [];
$form->_fromEmails = $fromEmailValues;
if (is_numeric(key($form->_fromEmails))) {
$emailID = (int) key($form->_fromEmails);
$defaults = CRM_Core_BAO_Email::getEmailSignatureDefaults($emailID);
}
if (!Civi::settings()->get('allow_mail_from_logged_in_contact')) {
$defaults['from_email_address'] = current(CRM_Core_BAO_Domain::getNameAndEmail(FALSE, TRUE));
}
$form->setDefaults($defaults);
}

/**
Expand Down Expand Up @@ -208,10 +197,8 @@ public function buildQuickForm() {
if ($to->getValue()) {
foreach ($this->getEmails($to) as $value) {
$contactId = $value['contact_id'];
$email = $value['email'];
if ($contactId) {
$this->_contactIds[] = $this->_toContactIds[] = $contactId;
$this->_toContactEmails[] = $email;
$this->_allContactIds[] = $contactId;
}
}
Expand Down Expand Up @@ -269,7 +256,7 @@ public function buildQuickForm() {

$this->add('text', 'subject', ts('Subject'), ['size' => 50, 'maxlength' => 254], TRUE);

$this->add('select', 'from_email_address', ts('From'), $this->_fromEmails, TRUE);
$this->add('select', 'from_email_address', ts('From'), $this->getFromEmails(), TRUE);

CRM_Mailing_BAO_Mailing::commonCompose($this);

Expand Down Expand Up @@ -353,6 +340,27 @@ public function buildQuickForm() {
CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Task/EmailCommon.js', 0, 'html-header');
}

/**
* Set relevant default values.
*
* @return array
*
* @throws \API_Exception
* @throws \CRM_Core_Exception
*/
public function setDefaultValues(): array {
$defaults = parent::setDefaultValues();
$fromEmails = $this->getFromEmails();
if (is_numeric(key($fromEmails))) {
$emailID = (int) key($fromEmails);
$defaults = CRM_Core_BAO_Email::getEmailSignatureDefaults($emailID);
}
if (!Civi::settings()->get('allow_mail_from_logged_in_contact')) {
$defaults['from_email_address'] = current(CRM_Core_BAO_Domain::getNameAndEmail(FALSE, TRUE));
}
return $defaults;
}

/**
* Process the form after the input has been submitted and validated.
*
Expand All @@ -363,8 +371,6 @@ public function buildQuickForm() {
*/
public function postProcess() {
$this->bounceIfSimpleMailLimitExceeded(count($this->_contactIds));

// check and ensure that
$formValues = $this->controller->exportValues($this->getName());
$this->submit($formValues);
}
Expand All @@ -375,7 +381,7 @@ public function postProcess() {
* @param int $count
* The number of emails the user is attempting to send
*/
protected function bounceIfSimpleMailLimitExceeded($count) {
protected function bounceIfSimpleMailLimitExceeded($count): void {
$limit = Civi::settings()->get('simple_mail_limit');
if ($count > $limit) {
CRM_Core_Error::statusBounce(ts('Please do not use this task to send a lot of emails (greater than %1). Many countries have legal requirements when sending bulk emails and the CiviMail framework has opt out functionality and domain tokens to help meet these.',
Expand All @@ -396,7 +402,7 @@ protected function bounceIfSimpleMailLimitExceeded($count) {
* @throws \Civi\API\Exception\UnauthorizedException
* @throws \API_Exception
*/
public function submit($formValues) {
public function submit($formValues): void {
$this->saveMessageTemplate($formValues);

$from = $formValues['from_email_address'] ?? NULL;
Expand All @@ -421,7 +427,7 @@ public function submit($formValues) {
if (!isset($this->_contactDetails[$contactId])) {
continue;
}
$email = $this->_toContactEmails[$key];
$email = $this->getEmail($key);
// prevent duplicate emails if same email address is selected CRM-4067
// we should allow same emails for different contacts
$details = $this->_contactDetails[$contactId];
Expand Down Expand Up @@ -726,4 +732,34 @@ protected function getCaseID(): ?int {
return NULL;
}

/**
* @return array
*/
protected function getFromEmails(): array {
$fromEmailValues = CRM_Core_BAO_Email::getFromEmail();

if (empty($fromEmailValues)) {
CRM_Core_Error::statusBounce(ts('Your user record does not have a valid email address and no from addresses have been configured.'));
}
return $fromEmailValues;
}

/**
* Get the relevant emails.
*
* @param int $index
*
* @return string
*/
protected function getEmail(int $index): string {
if (empty($this->emails)) {
$toEmails = explode(',', $this->getSubmittedValue('to'));
foreach ($toEmails as $value) {
$parts = explode('::', $value);
$this->emails[] = $parts[1];
}
}
return $this->emails[$index];
}

}
35 changes: 21 additions & 14 deletions tests/phpunit/CRM/Contact/Form/Task/EmailCommonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,6 @@ public function testPostProcessWithSignature(): void {

Civi::settings()->set('allow_mail_from_logged_in_contact', 1);
$loggedInContactID = $this->createLoggedInUser();
/* @var CRM_Contact_Form_Task_Email $form*/
$form = $this->getFormObject('CRM_Contact_Form_Task_Email');

for ($i = 0; $i < 27; $i++) {
$email = 'spy' . $i . '@secretsquirrels.com';
$contactID = $this->individualCreate(['email' => $email]);
$form->_contactIds[$contactID] = $contactID;
$form->_toContactEmails[$this->callAPISuccessGetValue('Email', ['return' => 'id', 'email' => $email])] = $email;
}
$deceasedContactID = $this->individualCreate(['is_deceased' => 1, 'email' => '[email protected]']);
$form->_contactIds[$deceasedContactID] = $deceasedContactID;
$form->_toContactEmails[$this->callAPISuccessGetValue('Email', ['return' => 'id', 'email' => '[email protected]'])] = '[email protected]';

$loggedInEmail = $this->callAPISuccess('Email', 'create', [
'email' => '[email protected]',
'location_type_id' => 1,
Expand All @@ -101,15 +88,35 @@ public function testPostProcessWithSignature(): void {
'signature_text' => 'This is a test Signature',
'signature_html' => '<p>This is a test Signature</p>',
]);

$to = $form_contactIds = $form_toContactEmails = [];
for ($i = 0; $i < 27; $i++) {
$email = 'spy' . $i . '@secretsquirrels.com';
$contactID = $this->individualCreate(['email' => $email]);
$form_contactIds[$contactID] = $contactID;
$to[] = $contactID . '::' . $email;
}
$deceasedContactID = $this->individualCreate(['is_deceased' => 1, 'email' => '[email protected]']);
$to[] = $deceasedContactID . '::' . '[email protected]';
/* @var CRM_Contact_Form_Task_Email $form*/
$form = $this->getFormObject('CRM_Contact_Form_Task_Email', [
'to' => implode(',', $to),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the key part of the change to this test - we are now passing 'to' as a submitted value rather than setting properties on the form (this is a good change)

]);
$form->_contactIds = $form_contactIds;
$form->_contactIds[$deceasedContactID] = $deceasedContactID;

$form->_allContactIds = $form->_toContactIds = $form->_contactIds;
$form->_emails = [$loggedInEmail['id'] => '[email protected]'];
$form->_fromEmails = [$loggedInEmail['id'] => '[email protected]'];
// This rule somehow disappears if there's a form-related test before us,
// so register it again. See packages/HTML/QuickForm/file.php.
// update - actually - it's never registered. Even in form made
// I can see it missing - It's really weird.
$form->registerRule('maxfilesize', 'callback', '_ruleCheckMaxFileSize', 'HTML_QuickForm_file');
$form->isSearchContext = FALSE;
$form->buildForm();
$form->submit(array_merge($form->_defaultValues, [
// @todo - it's better to pass these into getForm
// and access them on the form using $this->getSubmittedValue().
'from_email_address' => $loggedInEmail['id'],
'subject' => 'Really interesting stuff',
'bcc_id' => $bcc,
Expand Down
71 changes: 71 additions & 0 deletions tests/phpunit/CRM/Contribute/Form/Task/EmailTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/

/**
* Test Email task.
*
* @package CiviCRM_APIv3
* @subpackage API_Contribution
* @group headless
*/
class CRM_Contribute_Form_Task_EmailTest extends CiviUnitTestCase {

/**
* Clean up after each test.
*
* @throws \CRM_Core_Exception
* @throws \API_Exception
*/
public function tearDown(): void {
$this->quickCleanUpFinancialEntities();
parent::tearDown();
}

/**
* Test that email tokens are rendered.
*/
public function testEmailTokens(): void {
Civi::settings()->set('max_attachments', 0);
$contact1 = $this->individualCreate();
$contact2 = $this->individualCreate();
$userID = $this->createLoggedInUser();
Civi::settings()->set('allow_mail_from_logged_in_contact', TRUE);
$this->callAPISuccess('Email', 'create', [
'contact_id' => $userID,
'email' => '[email protected]',
'signature_html' => 'Benny, Benny',
'is_primary' => 1,
]);
$contribution1 = $this->contributionCreate(['contact_id' => $contact2]);
$contribution2 = $this->contributionCreate(['total_amount' => 999, 'contact_id' => $contact1]);
$form = $this->getFormObject('CRM_Contribute_Form_Task_Email', [
'cc_id' => '',
'bcc_id' => '',
'to' => implode(',', [
$contact1 . '::[email protected]',
$contact2 . '::[email protected]',
]),
'subject' => '{contact.display_name}',
'text_message' => '{contribution.total_amount}',
'html_message' => '{domain.name}',
], [], [
'radio_ts' => 'ts_sel',
'task' => CRM_Core_Task::TASK_EMAIL,
'mark_x_' . $contribution1 => 1,
'mark_x_' . $contribution2 => 1,
]);
$form->set('cid', $contact1 . ',' . $contact2);
$form->buildForm();
$this->assertEquals('<br/><br/>--Benny, Benny', $form->_defaultValues['html_message']);
$form->postProcess();
}

}