Skip to content

Commit

Permalink
CATL-1614: Add new field to the mail account form - Do not create new…
Browse files Browse the repository at this point in the history
… contacts when filing emails
  • Loading branch information
i-grou committed Oct 6, 2020
1 parent 7f76694 commit caca65b
Show file tree
Hide file tree
Showing 7 changed files with 293 additions and 53 deletions.
4 changes: 4 additions & 0 deletions CRM/Admin/Form/MailSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ public function buildQuickForm() {
];
$this->add('select', 'is_default', ts('Used For?'), $usedfor);
$this->addField('activity_status', ['placeholder' => FALSE]);

$this->add('checkbox', 'is_contact_creation_disabled_if_no_match', ts('Do not create new contacts when filing emails'));
}

/**
Expand Down Expand Up @@ -146,13 +148,15 @@ public function postProcess() {
'is_ssl',
'is_default',
'activity_status',
'is_contact_creation_disabled_if_no_match',
];

$params = [];
foreach ($fields as $f) {
if (in_array($f, [
'is_default',
'is_ssl',
'is_contact_creation_disabled_if_no_match',
])) {
$params[$f] = CRM_Utils_Array::value($f, $formValues, FALSE);
}
Expand Down
174 changes: 174 additions & 0 deletions CRM/Upgrade/Incremental/php/FiveThirtyOne.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
<?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 |
+--------------------------------------------------------------------+
*/

/**
* Upgrade logic for FiveThirtyOne */
class CRM_Upgrade_Incremental_php_FiveThirtyOne extends CRM_Upgrade_Incremental_Base {

/**
* Compute any messages which should be displayed beforeupgrade.
*
* Note: This function is called iteratively for each upcoming
* revision to the database.
*
* @param string $preUpgradeMessage
* @param string $rev
* a version number, e.g. '4.4.alpha1', '4.4.beta3', '4.4.0'.
* @param null $currentVer
*/
public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
// Example: Generate a pre-upgrade message.
// if ($rev == '5.12.34') {
// $preUpgradeMessage .= '<p>' . ts('A new permission, "%1", has been added. This permission is now used to control access to the Manage Tags screen.', array(1 => ts('manage tags'))) . '</p>';
// }
}

/**
* Compute any messages which should be displayed after upgrade.
*
* @param string $postUpgradeMessage
* alterable.
* @param string $rev
* an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
*/
public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
// Example: Generate a post-upgrade message.
// if ($rev == '5.12.34') {
// $postUpgradeMessage .= '<br /><br />' . ts("By default, CiviCRM now disables the ability to import directly from SQL. To use this feature, you must explicitly grant permission 'import SQL datasource'.");
// }
}

/*
* Important! All upgrade functions MUST add a 'runSql' task.
* Uncomment and use the following template for a new upgrade version
* (change the x in the function name):
*/

/**
* Upgrade function.
*
* @param string $rev
*/
public function upgrade_5_31_alpha1($rev) {
$this->addTask('Expand internal civicrm group title field to be 255 in length', 'grouptitlefieldExpand');
$this->addTask('Add in optional public title group table', 'addColumn', 'civicrm_group', 'frontend_title', "varchar(255) DEFAULT NULL COMMENT 'Alternative public title for this Group.'", TRUE, '5.31.alpha1', FALSE);
$this->addTask('Add in optional public description group table', 'addColumn', 'civicrm_group', 'frontend_description', "text DEFAULT NULL COMMENT 'Alternative public description of the group.'", TRUE, '5.31.alpha1');
$this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
$this->addTask('Remove Eway Single Currency Payment Processor type if not used or install the new extension for it', 'enableEwaySingleExtension');
$this->addTask('dev/core#1486 Remove FKs from ACL Cache tables', 'removeFKsFromACLCacheTables');
$this->addTask('Activate core extension "Greenwich"', 'installGreenwich');
}

/**
* Upgrade function.
*
* @param string $rev
*/
public function upgrade_5_31_0($rev) {
$this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
$this->addTask('Add is_contact_creation_disabled_if_no_match column to civicrm_mail_settings', 'addColumn',
'civicrm_mail_settings', 'is_contact_creation_disabled_if_no_match', "TINYINT DEFAULT 0 NOT NULL COMMENT 'If this option is enabled, CiviCRM will not create new contacts when filing emails'");
}

public static function enableEwaySingleExtension(CRM_Queue_TaskContext $ctx) {
$eWAYPaymentProcessorType = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_payment_processor_type WHERE class_name = 'Payment_eWAY'");
if ($eWAYPaymentProcessorType) {
$ewayPaymentProcessorCount = CRM_Core_DAO::singleValueQuery("SELECT count(id) FROM civicrm_payment_processor WHERE payment_processor_type_id = %1", [1 => [$eWAYPaymentProcessorType, 'Positive']]);
if ($ewayPaymentProcessorCount) {
$insert = CRM_Utils_SQL_Insert::into('civicrm_extension')->row([
'type' => 'module',
'full_name' => 'ewaysingle',
'name' => 'eway Single currency extension',
'label' => 'eway Single currency extension',
'file' => 'ewaysingle',
'schema_version' => NULL,
'is_active' => 1,
]);
CRM_Core_DAO::executeQuery($insert->usingReplace()->toSQL());
$managedEntity = CRM_Utils_SQL_Insert::into('civicrm_managed')->row([
'name' => 'eWAY',
'module' => 'ewaysingle',
'entity_type' => 'PaymentProcessorType',
'entity_id' => $eWAYPaymentProcessorType,
'cleanup' => NULL,
]);
CRM_Core_DAO::executeQuery($managedEntity->usingReplace()->toSQL());
}
else {
CRM_Core_DAO::executeQuery("DELETE FROM civicrm_payment_processor_type WHERE id = %1", [1 => [$eWAYPaymentProcessorType, 'Positive']]);
}
}
return TRUE;
}

public static function removeFKsFromACLCacheTables(CRM_Queue_TaskContext $ctx) {
CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_acl_contact_cache', 'FK_civicrm_acl_contact_cache_contact_id');
CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_acl_cache', 'FK_civicrm_acl_cache_contact_id');
CRM_Core_BAO_SchemaHandler::createIndexes(['civicrm_acl_cache' => ['contact_id']]);
return TRUE;
}

/**
* Install greenwich extensions.
*
* This feature is restructured as a core extension - which is primarily a code cleanup step.
*
* @param \CRM_Queue_TaskContext $ctx
*
* @return bool
*
* @throws \CRM_Core_Exception
*/
public static function installGreenwich(CRM_Queue_TaskContext $ctx) {
// Install via direct SQL manipulation. Note that:
// (1) This extension has no activation logic.
// (2) On new installs, the extension is activated purely via default SQL INSERT.
// (3) Caches are flushed at the end of the upgrade.
// ($) Over long term, upgrade steps are more reliable in SQL. API/BAO sometimes don't work mid-upgrade.
$insert = CRM_Utils_SQL_Insert::into('civicrm_extension')->row([
'type' => 'module',
'full_name' => 'greenwich',
'name' => 'Theme: Greenwich',
'label' => 'Theme: Greenwich',
'file' => 'greenwich',
'schema_version' => NULL,
'is_active' => 1,
]);
CRM_Core_DAO::executeQuery($insert->usingReplace()->toSQL());

return TRUE;
}

/**
* Expands the length of the civicrm_group.title field in the database to be 255.
*
* @param \CRM_Queue_TaskContext $ctx
*
* @return bool
*/
public static function grouptitlefieldExpand(CRM_Queue_TaskContext $ctx) {
$locales = CRM_Core_I18n::getMultilingual();
$queries = [];
if ($locales) {
foreach ($locales as $locale) {
$queries[] = "ALTER TABLE civicrm_group CHANGE `title_{$locale}` `title_{$locale}` varchar(255) NOT NULL COMMENT 'Name of Group.'";
}
}
else {
$queries[] = "ALTER TABLE civicrm_group CHANGE `title` `title` varchar(255) NOT NULL COMMENT 'Name of Group.'";
}
foreach ($queries as $query) {
CRM_Core_DAO::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
}
return TRUE;
}

}
27 changes: 16 additions & 11 deletions CRM/Utils/Mail/EmailProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public static function _process($civiMail, $dao, $is_create_activities) {
try {
$store = CRM_Mailing_MailStore::getStore($dao->name);
}
catch (Exception$e) {
catch (Exception $e) {
$message = ts('Could not connect to MailStore for ') . $dao->username . '@' . $dao->server . '<p>';
$message .= ts('Error message: ');
$message .= '<pre>' . $e->getMessage() . '</pre><p>';
Expand Down Expand Up @@ -226,7 +226,8 @@ public static function _process($civiMail, $dao, $is_create_activities) {
if ($usedfor == 0 || $is_create_activities) {
// if its the activities that needs to be processed ..
try {
$mailParams = CRM_Utils_Mail_Incoming::parseMailingObject($mail);
$createContact = !($dao->is_contact_creation_disabled_if_no_match ?? FALSE);
$mailParams = CRM_Utils_Mail_Incoming::parseMailingObject($mail, $createContact, FALSE);
}
catch (Exception $e) {
echo $e->getMessage();
Expand All @@ -241,16 +242,20 @@ public static function _process($civiMail, $dao, $is_create_activities) {
if (!empty($dao->activity_status)) {
$params['status_id'] = $dao->activity_status;
}
$result = civicrm_api('activity', 'create', $params);

if ($result['is_error']) {
$matches = FALSE;
echo "Failed Processing: {$mail->subject}. Reason: {$result['error_message']}\n";
}
else {
$matches = TRUE;
CRM_Utils_Hook::emailProcessor('activity', $params, $mail, $result);
echo "Processed as Activity: {$mail->subject}\n";
// Create activity if its not empty.
$matches = FALSE;
if (!empty($params['subject']) || !empty($params['target_contact_id'])) {
$result = civicrm_api('activity', 'create', $params);

if ($result['is_error']) {
echo "Failed Processing: {$mail->subject}. Reason: {$result['error_message']}\n";
}
else {
$matches = TRUE;
CRM_Utils_Hook::emailProcessor('activity', $params, $mail, $result);
echo "Processed as Activity: {$mail->subject}\n";
}
}
}

Expand Down
20 changes: 12 additions & 8 deletions CRM/Utils/Mail/Incoming.php
Original file line number Diff line number Diff line change
Expand Up @@ -322,10 +322,12 @@ public function &parse(&$file) {

/**
* @param $mail
* @param $createContact
* @param $requireContact
*
* @return array
*/
public static function parseMailingObject(&$mail) {
public static function parseMailingObject(&$mail, $createContact = TRUE, $requireContact = TRUE) {

$config = CRM_Core_Config::singleton();

Expand All @@ -342,18 +344,18 @@ public static function parseMailingObject(&$mail) {
}

$params['from'] = [];
self::parseAddress($mail->from, $field, $params['from'], $mail);
self::parseAddress($mail->from, $field, $params['from'], $mail, $createContact);

// we definitely need a contact id for the from address
// if we dont have one, skip this email
if (empty($params['from']['id'])) {
if ($requireContact && empty($params['from']['id'])) {
return NULL;
}

$emailFields = ['to', 'cc', 'bcc'];
foreach ($emailFields as $field) {
$value = $mail->$field;
self::parseAddresses($value, $field, $params, $mail);
self::parseAddresses($value, $field, $params, $mail, $createContact);
}

// define other parameters
Expand Down Expand Up @@ -396,8 +398,9 @@ public static function parseMailingObject(&$mail) {
* @param array $params
* @param $subParam
* @param $mail
* @param $createContact
*/
public static function parseAddress(&$address, &$params, &$subParam, &$mail) {
public static function parseAddress(&$address, &$params, &$subParam, &$mail, $createContact = TRUE) {
// CRM-9484
if (empty($address->email)) {
return;
Expand All @@ -408,7 +411,7 @@ public static function parseAddress(&$address, &$params, &$subParam, &$mail) {

$contactID = self::getContactID($subParam['email'],
$subParam['name'],
TRUE,
$createContact,
$mail
);
$subParam['id'] = $contactID ? $contactID : NULL;
Expand All @@ -419,13 +422,14 @@ public static function parseAddress(&$address, &$params, &$subParam, &$mail) {
* @param $token
* @param array $params
* @param $mail
* @param $createContact
*/
public static function parseAddresses(&$addresses, $token, &$params, &$mail) {
public static function parseAddresses(&$addresses, $token, &$params, &$mail, $createContact = TRUE) {
$params[$token] = [];

foreach ($addresses as $address) {
$subParam = [];
self::parseAddress($address, $params, $subParam, $mail);
self::parseAddress($address, $params, $subParam, $mail, $createContact);
$params[$token][] = $subParam;
}
}
Expand Down
Loading

0 comments on commit caca65b

Please sign in to comment.