3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\Api4\SubscriptionHistory
;
13 use Civi\Core\Event\PostEvent
;
14 use Civi\Core\HookInterface
;
19 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 class CRM_Contact_BAO_GroupContact
extends CRM_Contact_DAO_GroupContact
implements HookInterface
{
24 * Deprecated add function
26 * @param array $params
28 * @return CRM_Contact_DAO_GroupContact
29 * @throws \CRM_Core_Exception
33 public static function add(array $params): CRM_Contact_DAO_GroupContact
{
34 return self
::writeRecord($params);
38 * Callback for hook_civicrm_post().
40 * @param \Civi\Core\Event\PostEvent $event
42 * @noinspection PhpUnused
43 * @noinspection UnknownInspectionInspection
45 public static function self_hook_civicrm_post(PostEvent
$event): void
{
46 if (is_object($event->object) && in_array($event->action
, ['create', 'edit'], TRUE)) {
47 // Lookup existing info for the sake of subscription history
48 if ($event->action
=== 'edit') {
49 $event->object->find(TRUE);
53 if (empty($event->object->group_id
) ||
empty($event->object->contact_id
) ||
empty($event->object->status
)) {
54 $event->object->find(TRUE);
56 SubscriptionHistory
::save(FALSE)->setRecords([
58 'group_id' => $event->object->group_id
,
59 'contact_id' => $event->object->contact_id
,
60 'status' => $event->object->status
,
64 catch (API_Exception
$e) {
65 // A failure to create the history might be a deadlock or similar
66 // This record is not important enough to trigger a larger fail.
67 Civi
::log()->warning('Failed to add civicrm_subscription_history record with error :error', ['error' => $e->getMessage()]);
73 * Given the list of params in the params array, fetch the object
74 * and store the values in the values array
76 * @param array $params
77 * Input parameters to find object.
78 * @param array $values
79 * Output values of the object.
82 * (reference) the values that could be potentially assigned to smarty
84 public static function getValues($params, &$values) {
88 $values['group']['data'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
93 // get the total count of groups
94 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
104 * Given an array of contact ids, add all the contacts to the group
106 * @param array $contactIds
107 * The array of contact ids to be added.
108 * @param int $groupId
109 * The id of the group.
110 * @param string $method
111 * @param string $status
112 * @param int $tracking
115 * (total, added, notAdded) count of contacts added to group
117 public static function addContactsToGroup(
124 if (empty($contactIds) ||
empty($groupId)) {
128 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
130 $result = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
131 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($groupId);
132 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
134 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
136 return [count($contactIds), $result['count_added'], $result['count_not_added']];
140 * Given an array of contact ids, remove all the contacts from the group
142 * @param array $contactIds
143 * (reference ) the array of contact ids to be removed.
144 * @param int $groupId
145 * The id of the group.
147 * @param string $method
148 * @param string $status
149 * @param string $tracking
152 * (total, removed, notRemoved) count of contacts removed to group
154 public static function removeContactsFromGroup(
161 if (!is_array($contactIds)) {
164 if ($status == 'Removed' ||
$status == 'Deleted') {
171 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
173 $date = date('YmdHis');
174 $numContactsRemoved = 0;
175 $numContactsNotRemoved = 0;
177 $group = new CRM_Contact_DAO_Group();
178 $group->id
= $groupId;
181 foreach ($contactIds as $contactId) {
182 if ($status == 'Deleted') {
183 $query = "DELETE FROM civicrm_group_contact WHERE contact_id = %1 AND group_id = %2";
184 $dao = CRM_Core_DAO
::executeQuery($query, [
185 1 => [$contactId, 'Positive'],
186 2 => [$groupId, 'Positive'],
189 'group_id' => $groupId,
190 'contact_id' => $contactId,
194 'tracking' => $tracking,
196 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
197 // Removing a row from civicrm_group_contact for a smart group may mean a contact
198 // Is now back in a group based on criteria so we will invalidate the cache if it is there
199 // So that accurate group cache is created next time it is needed.
200 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($groupId);
203 $groupContact = new CRM_Contact_DAO_GroupContact();
204 $groupContact->group_id
= $groupId;
205 $groupContact->contact_id
= $contactId;
206 // check if the selected contact id already a member, or if this is
207 // an opt-out of a smart group.
208 // if not a member remove to groupContact else keep the count of contacts that are not removed
209 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
210 // remove the contact from the group
211 $numContactsRemoved++
;
214 $numContactsNotRemoved++
;
217 //now we grant the negative membership to contact if not member. CRM-3711
219 'group_id' => $groupId,
220 'contact_id' => $contactId,
224 'tracking' => $tracking,
226 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
227 $groupContact->status
= $status;
228 $groupContact->save();
229 // Remove any rows from the group contact cache so it disappears straight away from smart groups.
230 CRM_Contact_BAO_GroupContactCache
::removeContact($contactId, $groupId);
234 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
236 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
238 return [count($contactIds), $numContactsRemoved, $numContactsNotRemoved];
242 * Get list of all the groups and groups for a contact.
244 * @param int $contactId
247 * @param bool $visibility
251 * this array has key-> group id and value group title
253 public static function getGroupList($contactId = 0, $visibility = FALSE) {
254 $select = 'SELECT civicrm_group.id, civicrm_group.title ';
255 $from = ' FROM civicrm_group ';
256 $where = " WHERE civicrm_group.is_active = 1 ";
258 $from .= ' , civicrm_group_contact ';
259 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
260 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
264 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
266 $groupBy = " GROUP BY civicrm_group.id";
268 $orderby = " ORDER BY civicrm_group.name";
269 $sql = $select . $from . $where . $groupBy . $orderby;
271 $group = CRM_Core_DAO
::executeQuery($sql);
274 while ($group->fetch()) {
275 $values[$group->id
] = $group->title
;
282 * Get the list of groups for contact based on status of group membership.
284 * @param int $contactId
286 * @param string $status
287 * State of membership.
288 * @param int $numGroupContact
289 * Number of groups for a contact that should be shown.
291 * True if we are interested only in the count.
292 * @param bool $ignorePermission
293 * True if we should ignore permissions for the current user.
294 * useful in profile where permissions are limited for the user. If left
295 * at false only groups viewable by the current user are returned
296 * @param bool $onlyPublicGroups
297 * True if we want to hide system groups.
299 * @param bool $excludeHidden
301 * @param int $groupId
303 * @param bool $includeSmartGroups
304 * Include or Exclude Smart Group(s)
305 * @param bool $public
306 * Are we returning groups for use on a public page.
309 * the relevant data object values for the contact or the total count when $count is TRUE
311 public static function getContactGroup(
314 $numGroupContact = NULL,
316 $ignorePermission = FALSE,
317 $onlyPublicGroups = FALSE,
318 $excludeHidden = TRUE,
320 $includeSmartGroups = FALSE,
324 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
328 civicrm_group_contact.id as civicrm_group_contact_id,
329 civicrm_group.title as group_title,
330 civicrm_group.frontend_title as group_public_title,
331 civicrm_group.visibility as visibility,
332 civicrm_group_contact.status as status,
333 civicrm_group.id as group_id,
334 civicrm_group.is_hidden as is_hidden,
335 civicrm_subscription_history.date as date,
336 civicrm_subscription_history.method as method';
339 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
340 if (!$includeSmartGroups) {
341 $where .= " AND saved_search_id IS NULL";
343 if ($excludeHidden) {
344 $where .= " AND civicrm_group.is_hidden = 0 ";
346 $params = [1 => [$contactId, 'Integer']];
347 if (!empty($status)) {
348 $where .= ' AND civicrm_group_contact.status = %2';
349 $params[2] = [$status, 'String'];
351 if (!empty($groupId)) {
352 $where .= " AND civicrm_group.id = %3 ";
353 $params[3] = [$groupId, 'Integer'];
356 'civicrm_group_contact' => 1,
357 'civicrm_group' => 1,
358 'civicrm_subscription_history' => 1,
361 if ($ignorePermission) {
362 $permission = ' ( 1 ) ';
365 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
368 $from = CRM_Contact_BAO_Query
::fromClause($tables);
370 $where .= " AND $permission ";
372 if ($onlyPublicGroups) {
373 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
376 $order = $limit = '';
378 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
380 if ($numGroupContact) {
381 $limit = " LIMIT 0, $numGroupContact";
385 $sql = $select . $from . $where . $order . $limit;
388 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
392 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
394 while ($dao->fetch()) {
395 $id = $dao->civicrm_group_contact_id
;
396 $values[$id]['id'] = $id;
397 $values[$id]['group_id'] = $dao->group_id
;
398 $values[$id]['title'] = ($public && !empty($group->group_public_title
) ?
$group->group_public_title
: $dao->group_title
);
399 $values[$id]['visibility'] = $dao->visibility
;
400 $values[$id]['is_hidden'] = $dao->is_hidden
;
401 switch ($dao->status
) {
411 $prefix = 'pending_';
413 $values[$id][$prefix . 'date'] = $dao->date
;
414 $values[$id][$prefix . 'method'] = $dao->method
;
415 if ($status == 'Removed') {
416 $query = "SELECT `date` as `date_added` FROM civicrm_subscription_history WHERE id = (SELECT max(id) FROM civicrm_subscription_history WHERE contact_id = %1 AND status = \"Added\" AND group_id = $dao->group_id )";
417 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
418 if ($dateDAO->fetch()) {
419 $values[$id]['date_added'] = $dateDAO->date_added
;
428 * Returns membership details of a contact for a group.
430 * @param int $contactId
432 * @param int $groupID
433 * Id of a particular group.
434 * @param string $method
435 * If we want the subscription history details for a specific method.
440 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
441 $leftJoin = $where = $orderBy = NULL;
444 //CRM-13341 add group_id clause
446 LEFT JOIN civicrm_subscription_history
447 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
448 AND civicrm_subscription_history.group_id = {$groupID} )";
449 $where = "AND civicrm_subscription_history.method ='Email'";
450 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
454 FROM civicrm_group_contact
456 WHERE civicrm_group_contact.contact_id = %1
457 AND civicrm_group_contact.group_id = %2
463 1 => [$contactId, 'Integer'],
464 2 => [$groupID, 'Integer'],
466 $dao = CRM_Core_DAO
::executeQuery($query, $params);
472 * Method to get Group Id.
474 * @param int $groupContactID
475 * Id of a particular group.
478 * @return int groupID
480 public static function getGroupId($groupContactID) {
481 $dao = new CRM_Contact_DAO_GroupContact();
482 $dao->id
= $groupContactID;
484 return $dao->group_id
;
488 * Deprecated create function.
492 * @param array $params
494 * @return CRM_Contact_DAO_GroupContact
496 public static function create(array $params) {
497 // @fixme create was only called from CRM_Contact_BAO_Contact::createProfileContact
498 // As of Aug 2020 it's not called from anywhere so we can remove the below code after some time
500 CRM_Core_Error
::deprecatedFunctionWarning('Use the GroupContact API');
501 return self
::add($params);
505 * @param int $contactID
506 * @param int $groupID
510 public static function isContactInGroup($contactID, $groupID) {
511 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
512 !CRM_Utils_Rule
::positiveInteger($groupID)
518 ['group', 'IN', [$groupID], 0, 0],
519 ['contact_id', '=', $contactID, 0, 0],
521 [$contacts] = CRM_Contact_BAO_Query
::apiQuery($params, ['contact_id']);
523 if (!empty($contacts)) {
530 * Function merges the groups from otherContactID to mainContactID.
531 * along with subscription history
533 * @param int $mainContactId
534 * Contact id of main contact record.
535 * @param int $otherContactId
536 * Contact id of record which is going to merge.
538 * @see CRM_Dedupe_Merger::cpTables()
540 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
542 public static function mergeGroupContact($mainContactId, $otherContactId) {
544 1 => [$mainContactId, 'Integer'],
545 2 => [$otherContactId, 'Integer'],
548 // find all groups that are in otherContactID but not in mainContactID, copy them over
550 SELECT cOther.group_id
551 FROM civicrm_group_contact cOther
552 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
553 WHERE cOther.contact_id = %2
554 AND cMain.contact_id IS NULL
556 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
559 while ($dao->fetch()) {
560 $otherGroupIDs[] = $dao->group_id
;
563 if (!empty($otherGroupIDs)) {
564 $otherGroupIDString = implode(',', $otherGroupIDs);
567 UPDATE civicrm_group_contact
569 WHERE contact_id = %2
570 AND group_id IN ( $otherGroupIDString )
572 CRM_Core_DAO
::executeQuery($sql, $params);
575 UPDATE civicrm_subscription_history
577 WHERE contact_id = %2
578 AND group_id IN ( $otherGroupIDString )
580 CRM_Core_DAO
::executeQuery($sql, $params);
584 SELECT cOther.group_id as group_id,
585 cOther.status as group_status
586 FROM civicrm_group_contact cMain
587 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
588 WHERE cMain.contact_id = %1
589 AND cOther.contact_id = %2
591 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
594 while ($dao->fetch()) {
595 // only copy it over if it has added status and migrate the history
596 if ($dao->group_status
== 'Added') {
597 $groupIDs[] = $dao->group_id
;
601 if (!empty($groupIDs)) {
602 $groupIDString = implode(',', $groupIDs);
605 UPDATE civicrm_group_contact
607 WHERE contact_id = %1
608 AND group_id IN ( $groupIDString )
610 CRM_Core_DAO
::executeQuery($sql, $params);
613 UPDATE civicrm_subscription_history
615 WHERE contact_id = %2
616 AND group_id IN ( $groupIDString )
618 CRM_Core_DAO
::executeQuery($sql, $params);
621 // delete all the other group contacts
624 FROM civicrm_group_contact
625 WHERE contact_id = %2
627 CRM_Core_DAO
::executeQuery($sql, $params);
631 FROM civicrm_subscription_history
632 WHERE contact_id = %2
634 CRM_Core_DAO
::executeQuery($sql, $params);
638 * Given an array of contact ids, add all the contacts to the group
640 * @param array $contactIDs
641 * The array of contact ids to be added.
642 * @param int $groupID
643 * The id of the group.
644 * @param string $method
645 * @param string $status
646 * @param string $tracking
649 * (total, added, notAdded) count of contacts added to group
651 public static function bulkAddContactsToGroup(
659 $numContactsAdded = 0;
660 $numContactsNotAdded = 0;
663 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
666 $subscriptioHistorySQL = "
667 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
671 $date = date('YmdHis');
673 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
674 while (!empty($contactIDs)) {
675 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
676 $contactStr = implode(',', $input);
678 // lets check their current status
680 SELECT GROUP_CONCAT(contact_id) as contactStr
681 FROM civicrm_group_contact
684 AND contact_id IN ( $contactStr )
687 1 => [$groupID, 'Integer'],
688 2 => [$status, 'String'],
692 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
694 $presentIDs = explode(',', ($dao->contactStr ??
''));
695 $presentIDs = array_flip($presentIDs);
698 $gcValues = $shValues = [];
699 foreach ($input as $cid) {
700 if (isset($presentIDs[$cid])) {
701 $numContactsNotAdded++
;
705 $gcValues[] = "( $groupID, $cid, '$status' )";
706 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
710 if (!empty($gcValues)) {
711 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
712 CRM_Core_DAO
::executeQuery($cgSQL);
714 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
715 CRM_Core_DAO
::executeQuery($shSQL);
719 return ['count_added' => $numContactsAdded, 'count_not_added' => $numContactsNotAdded];
723 * Get options for a given field.
724 * @see CRM_Core_DAO::buildOptions
726 * @param string $fieldName
727 * @param string $context
728 * @see CRM_Core_DAO::buildOptionsContext
729 * @param array $props
730 * whatever is known about this dao object.
734 public static function buildOptions($fieldName, $context = NULL, $props = []) {
735 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, [], $context);
737 // Sort group list by hierarchy
738 // TODO: This will only work when api.entity is "group_contact". What about others?
739 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
740 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);