Invalidate smart group cache for group following deletion of group_contact row
authorSeamus Lee <seamuslee001@gmail.com>
Fri, 28 Jun 2019 22:45:42 +0000 (08:45 +1000)
committerSeamus Lee <seamuslee001@gmail.com>
Wed, 24 Jul 2019 21:51:52 +0000 (07:51 +1000)
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
CRM/Contact/BAO/GroupContactCache.php

index 2e1dbd503b62306c52c87fd78a57e661e7836a9f..bb9d9ec163ecbfd4dced6bb0bb623f7191f7a323 100644 (file)
@@ -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();
index a54dcdeb43fcbaf51ec3aa5e7c9cefb5e682bcc5..25f69b01a35674cc0e7bb0980dd8280d969ed91e 100644 (file)
@@ -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'],
+      ]);
+  }
+
 }