From dadeae7d3572940b30d02c2c570bcbd3645958fd Mon Sep 17 00:00:00 2001 From: Seamus Lee Date: Sat, 29 Jun 2019 08:45:42 +1000 Subject: [PATCH] Invalidate smart group cache for group following deletion of group_contact row Add in function to invalidate smart group cache rather than building it up again when contact removal is deleted Remove if check --- CRM/Contact/BAO/GroupContact.php | 12 +++++++++--- CRM/Contact/BAO/GroupContactCache.php | 12 ++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/CRM/Contact/BAO/GroupContact.php b/CRM/Contact/BAO/GroupContact.php index 2e1dbd503b..bb9d9ec163 100644 --- a/CRM/Contact/BAO/GroupContact.php +++ b/CRM/Contact/BAO/GroupContact.php @@ -180,7 +180,6 @@ class CRM_Contact_BAO_GroupContact extends CRM_Contact_DAO_GroupContact { if (!is_array($contactIds)) { return [0, 0, 0]; } - if ($status == 'Removed' || $status == 'Deleted') { $op = 'delete'; } @@ -200,8 +199,11 @@ class CRM_Contact_BAO_GroupContact extends CRM_Contact_DAO_GroupContact { foreach ($contactIds as $contactId) { if ($status == 'Deleted') { - $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId"; - $dao = CRM_Core_DAO::executeQuery($query); + $query = "DELETE FROM civicrm_group_contact WHERE contact_id = %1 AND group_id = %2"; + $dao = CRM_Core_DAO::executeQuery($query, [ + 1 => [$contactId, 'Positive'], + 2 => [$groupId, 'Positive'], + ]); $historyParams = [ 'group_id' => $groupId, 'contact_id' => $contactId, @@ -211,6 +213,10 @@ class CRM_Contact_BAO_GroupContact extends CRM_Contact_DAO_GroupContact { 'tracking' => $tracking, ]; CRM_Contact_BAO_SubscriptionHistory::create($historyParams); + // Removing a row from civicrm_group_contact for a smart group may mean a contact + // Is now back in a group based on criteria so we will invalidate the cache if it is there + // So that accurate group cache is created next time it is needed. + CRM_Contact_BAO_GroupContactCache::invalidateGroupContactCache($groupId); } else { $groupContact = new CRM_Contact_DAO_GroupContact(); diff --git a/CRM/Contact/BAO/GroupContactCache.php b/CRM/Contact/BAO/GroupContactCache.php index a54dcdeb43..25f69b01a3 100644 --- a/CRM/Contact/BAO/GroupContactCache.php +++ b/CRM/Contact/BAO/GroupContactCache.php @@ -760,4 +760,16 @@ ORDER BY gc.contact_id, g.children return date('YmdHis', strtotime("+ " . self::smartGroupCacheTimeout() . " Minutes")); } + /** + * Invalidates the smart group cache for a particular group + * @param int $groupID - Group to invalidate + */ + public static function invalidateGroupContactCache($groupID) { + CRM_Core_DAO::executeQuery("UPDATE civicrm_group + SET cache_date = NULL, refresh_date = NULL + WHERE id = %1", [ + 1 => [$groupID, 'Positive'], + ]); + } + } -- 2.25.1