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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contact_BAO_GroupContact
extends CRM_Contact_DAO_GroupContact
{
20 * Takes an associative array and creates a groupContact object.
22 * the function extract all the params it needs to initialize the create a
23 * group object. the params array could contain additional unused name/value
26 * @param array $params
27 * (reference ) an assoc array of name/value pairs.
29 * @return CRM_Contact_BAO_GroupContact
31 public static function add($params) {
32 $hook = empty($params['id']) ?
'create' : 'edit';
33 CRM_Utils_Hook
::pre($hook, 'GroupContact', CRM_Utils_Array
::value('id', $params), $params);
35 if (!self
::dataExists($params)) {
39 $groupContact = new CRM_Contact_BAO_GroupContact();
40 $groupContact->copyValues($params);
41 $groupContact->save();
43 // Lookup existing info for the sake of subscription history
44 if (!empty($params['id'])) {
45 $groupContact->find(TRUE);
46 $params = $groupContact->toArray();
48 CRM_Contact_BAO_SubscriptionHistory
::create($params);
50 CRM_Utils_Hook
::post($hook, 'GroupContact', $groupContact->id
, $groupContact);
56 * Check if there is data to create the object.
58 * @param array $params
59 * (reference ) an assoc array of name/value pairs.
63 public static function dataExists(&$params) {
64 return (!empty($params['id']) ||
(!empty($params['group_id']) && !empty($params['contact_id'])));
68 * Given the list of params in the params array, fetch the object
69 * and store the values in the values array
71 * @param array $params
72 * Input parameters to find object.
73 * @param array $values
74 * Output values of the object.
77 * (reference) the values that could be potentially assigned to smarty
79 public static function getValues($params, &$values) {
83 $values['group']['data'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
88 // get the total count of groups
89 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
99 * Given an array of contact ids, add all the contacts to the group
101 * @param array $contactIds
102 * The array of contact ids to be added.
103 * @param int $groupId
104 * The id of the group.
105 * @param string $method
106 * @param string $status
107 * @param int $tracking
110 * (total, added, notAdded) count of contacts added to group
112 public static function addContactsToGroup(
119 if (empty($contactIds) ||
empty($groupId)) {
123 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
125 $result = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
126 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($groupId);
127 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
129 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
131 return [count($contactIds), $result['count_added'], $result['count_not_added']];
135 * Given an array of contact ids, remove all the contacts from the group
137 * @param array $contactIds
138 * (reference ) the array of contact ids to be removed.
139 * @param int $groupId
140 * The id of the group.
142 * @param string $method
143 * @param string $status
144 * @param string $tracking
147 * (total, removed, notRemoved) count of contacts removed to group
149 public static function removeContactsFromGroup(
156 if (!is_array($contactIds)) {
159 if ($status == 'Removed' ||
$status == 'Deleted') {
166 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
168 $date = date('YmdHis');
169 $numContactsRemoved = 0;
170 $numContactsNotRemoved = 0;
172 $group = new CRM_Contact_DAO_Group();
173 $group->id
= $groupId;
176 foreach ($contactIds as $contactId) {
177 if ($status == 'Deleted') {
178 $query = "DELETE FROM civicrm_group_contact WHERE contact_id = %1 AND group_id = %2";
179 $dao = CRM_Core_DAO
::executeQuery($query, [
180 1 => [$contactId, 'Positive'],
181 2 => [$groupId, 'Positive'],
184 'group_id' => $groupId,
185 'contact_id' => $contactId,
189 'tracking' => $tracking,
191 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
192 // Removing a row from civicrm_group_contact for a smart group may mean a contact
193 // Is now back in a group based on criteria so we will invalidate the cache if it is there
194 // So that accurate group cache is created next time it is needed.
195 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($groupId);
198 $groupContact = new CRM_Contact_DAO_GroupContact();
199 $groupContact->group_id
= $groupId;
200 $groupContact->contact_id
= $contactId;
201 // check if the selected contact id already a member, or if this is
202 // an opt-out of a smart group.
203 // if not a member remove to groupContact else keep the count of contacts that are not removed
204 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
205 // remove the contact from the group
206 $numContactsRemoved++
;
209 $numContactsNotRemoved++
;
212 //now we grant the negative membership to contact if not member. CRM-3711
214 'group_id' => $groupId,
215 'contact_id' => $contactId,
219 'tracking' => $tracking,
221 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
222 $groupContact->status
= $status;
223 $groupContact->save();
224 // Remove any rows from the group contact cache so it disappears straight away from smart groups.
225 CRM_Contact_BAO_GroupContactCache
::removeContact($contactId, $groupId);
229 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
231 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
233 return [count($contactIds), $numContactsRemoved, $numContactsNotRemoved];
237 * Get list of all the groups and groups for a contact.
239 * @param int $contactId
242 * @param bool $visibility
246 * this array has key-> group id and value group title
248 public static function getGroupList($contactId = 0, $visibility = FALSE) {
249 $select = 'SELECT civicrm_group.id, civicrm_group.title ';
250 $from = ' FROM civicrm_group ';
251 $where = " WHERE civicrm_group.is_active = 1 ";
253 $from .= ' , civicrm_group_contact ';
254 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
255 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
259 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
261 $groupBy = " GROUP BY civicrm_group.id";
263 $orderby = " ORDER BY civicrm_group.name";
264 $sql = $select . $from . $where . $groupBy . $orderby;
266 $group = CRM_Core_DAO
::executeQuery($sql);
269 while ($group->fetch()) {
270 $values[$group->id
] = $group->title
;
277 * Get the list of groups for contact based on status of group membership.
279 * @param int $contactId
281 * @param string $status
282 * State of membership.
283 * @param int $numGroupContact
284 * Number of groups for a contact that should be shown.
286 * True if we are interested only in the count.
287 * @param bool $ignorePermission
288 * True if we should ignore permissions for the current user.
289 * useful in profile where permissions are limited for the user. If left
290 * at false only groups viewable by the current user are returned
291 * @param bool $onlyPublicGroups
292 * True if we want to hide system groups.
294 * @param bool $excludeHidden
296 * @param int $groupId
298 * @param bool $includeSmartGroups
299 * Include or Exclude Smart Group(s)
300 * @param bool $public
301 * Are we returning groups for use on a public page.
304 * the relevant data object values for the contact or the total count when $count is TRUE
306 public static function getContactGroup(
309 $numGroupContact = NULL,
311 $ignorePermission = FALSE,
312 $onlyPublicGroups = FALSE,
313 $excludeHidden = TRUE,
315 $includeSmartGroups = FALSE,
319 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
323 civicrm_group_contact.id as civicrm_group_contact_id,
324 civicrm_group.title as group_title,
325 civicrm_group.frontend_title as group_public_title,
326 civicrm_group.visibility as visibility,
327 civicrm_group_contact.status as status,
328 civicrm_group.id as group_id,
329 civicrm_group.is_hidden as is_hidden,
330 civicrm_subscription_history.date as date,
331 civicrm_subscription_history.method as method';
334 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
335 if (!$includeSmartGroups) {
336 $where .= " AND saved_search_id IS NULL";
338 if ($excludeHidden) {
339 $where .= " AND civicrm_group.is_hidden = 0 ";
341 $params = [1 => [$contactId, 'Integer']];
342 if (!empty($status)) {
343 $where .= ' AND civicrm_group_contact.status = %2';
344 $params[2] = [$status, 'String'];
346 if (!empty($groupId)) {
347 $where .= " AND civicrm_group.id = %3 ";
348 $params[3] = [$groupId, 'Integer'];
351 'civicrm_group_contact' => 1,
352 'civicrm_group' => 1,
353 'civicrm_subscription_history' => 1,
356 if ($ignorePermission) {
357 $permission = ' ( 1 ) ';
360 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
363 $from = CRM_Contact_BAO_Query
::fromClause($tables);
365 $where .= " AND $permission ";
367 if ($onlyPublicGroups) {
368 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
371 $order = $limit = '';
373 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
375 if ($numGroupContact) {
376 $limit = " LIMIT 0, $numGroupContact";
380 $sql = $select . $from . $where . $order . $limit;
383 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
387 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
389 while ($dao->fetch()) {
390 $id = $dao->civicrm_group_contact_id
;
391 $values[$id]['id'] = $id;
392 $values[$id]['group_id'] = $dao->group_id
;
393 $values[$id]['title'] = ($public && !empty($group->group_public_title
) ?
$group->group_public_title
: $dao->group_title
);
394 $values[$id]['visibility'] = $dao->visibility
;
395 $values[$id]['is_hidden'] = $dao->is_hidden
;
396 switch ($dao->status
) {
406 $prefix = 'pending_';
408 $values[$id][$prefix . 'date'] = $dao->date
;
409 $values[$id][$prefix . 'method'] = $dao->method
;
410 if ($status == 'Removed') {
411 $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 )";
412 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
413 if ($dateDAO->fetch()) {
414 $values[$id]['date_added'] = $dateDAO->date_added
;
423 * Returns membership details of a contact for a group.
425 * @param int $contactId
427 * @param int $groupID
428 * Id of a particular group.
429 * @param string $method
430 * If we want the subscription history details for a specific method.
435 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
436 $leftJoin = $where = $orderBy = NULL;
439 //CRM-13341 add group_id clause
441 LEFT JOIN civicrm_subscription_history
442 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
443 AND civicrm_subscription_history.group_id = {$groupID} )";
444 $where = "AND civicrm_subscription_history.method ='Email'";
445 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
449 FROM civicrm_group_contact
451 WHERE civicrm_group_contact.contact_id = %1
452 AND civicrm_group_contact.group_id = %2
458 1 => [$contactId, 'Integer'],
459 2 => [$groupID, 'Integer'],
461 $dao = CRM_Core_DAO
::executeQuery($query, $params);
467 * Method to get Group Id.
469 * @param int $groupContactID
470 * Id of a particular group.
473 * @return int groupID
475 public static function getGroupId($groupContactID) {
476 $dao = new CRM_Contact_DAO_GroupContact();
477 $dao->id
= $groupContactID;
479 return $dao->group_id
;
483 * Deprecated create function.
487 * @param array $params
489 * @return CRM_Contact_BAO_GroupContact
491 public static function create(array $params) {
492 // @fixme create was only called from CRM_Contact_BAO_Contact::createProfileContact
493 // As of Aug 2020 it's not called from anywhere so we can remove the below code after some time
495 CRM_Core_Error
::deprecatedFunctionWarning('Use the GroupContact API');
496 return self
::add($params);
500 * @param int $contactID
501 * @param int $groupID
505 public static function isContactInGroup($contactID, $groupID) {
506 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
507 !CRM_Utils_Rule
::positiveInteger($groupID)
513 ['group', 'IN', [$groupID], 0, 0],
514 ['contact_id', '=', $contactID, 0, 0],
516 [$contacts] = CRM_Contact_BAO_Query
::apiQuery($params, ['contact_id']);
518 if (!empty($contacts)) {
525 * Function merges the groups from otherContactID to mainContactID.
526 * along with subscription history
528 * @param int $mainContactId
529 * Contact id of main contact record.
530 * @param int $otherContactId
531 * Contact id of record which is going to merge.
533 * @see CRM_Dedupe_Merger::cpTables()
535 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
537 public static function mergeGroupContact($mainContactId, $otherContactId) {
539 1 => [$mainContactId, 'Integer'],
540 2 => [$otherContactId, 'Integer'],
543 // find all groups that are in otherContactID but not in mainContactID, copy them over
545 SELECT cOther.group_id
546 FROM civicrm_group_contact cOther
547 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
548 WHERE cOther.contact_id = %2
549 AND cMain.contact_id IS NULL
551 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
554 while ($dao->fetch()) {
555 $otherGroupIDs[] = $dao->group_id
;
558 if (!empty($otherGroupIDs)) {
559 $otherGroupIDString = implode(',', $otherGroupIDs);
562 UPDATE civicrm_group_contact
564 WHERE contact_id = %2
565 AND group_id IN ( $otherGroupIDString )
567 CRM_Core_DAO
::executeQuery($sql, $params);
570 UPDATE civicrm_subscription_history
572 WHERE contact_id = %2
573 AND group_id IN ( $otherGroupIDString )
575 CRM_Core_DAO
::executeQuery($sql, $params);
579 SELECT cOther.group_id as group_id,
580 cOther.status as group_status
581 FROM civicrm_group_contact cMain
582 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
583 WHERE cMain.contact_id = %1
584 AND cOther.contact_id = %2
586 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
589 while ($dao->fetch()) {
590 // only copy it over if it has added status and migrate the history
591 if ($dao->group_status
== 'Added') {
592 $groupIDs[] = $dao->group_id
;
596 if (!empty($groupIDs)) {
597 $groupIDString = implode(',', $groupIDs);
600 UPDATE civicrm_group_contact
602 WHERE contact_id = %1
603 AND group_id IN ( $groupIDString )
605 CRM_Core_DAO
::executeQuery($sql, $params);
608 UPDATE civicrm_subscription_history
610 WHERE contact_id = %2
611 AND group_id IN ( $groupIDString )
613 CRM_Core_DAO
::executeQuery($sql, $params);
616 // delete all the other group contacts
619 FROM civicrm_group_contact
620 WHERE contact_id = %2
622 CRM_Core_DAO
::executeQuery($sql, $params);
626 FROM civicrm_subscription_history
627 WHERE contact_id = %2
629 CRM_Core_DAO
::executeQuery($sql, $params);
633 * Given an array of contact ids, add all the contacts to the group
635 * @param array $contactIDs
636 * The array of contact ids to be added.
637 * @param int $groupID
638 * The id of the group.
639 * @param string $method
640 * @param string $status
641 * @param string $tracking
644 * (total, added, notAdded) count of contacts added to group
646 public static function bulkAddContactsToGroup(
654 $numContactsAdded = 0;
655 $numContactsNotAdded = 0;
658 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
661 $subscriptioHistorySQL = "
662 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
666 $date = date('YmdHis');
668 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
669 while (!empty($contactIDs)) {
670 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
671 $contactStr = implode(',', $input);
673 // lets check their current status
675 SELECT GROUP_CONCAT(contact_id) as contactStr
676 FROM civicrm_group_contact
679 AND contact_id IN ( $contactStr )
682 1 => [$groupID, 'Integer'],
683 2 => [$status, 'String'],
687 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
689 $presentIDs = explode(',', $dao->contactStr
);
690 $presentIDs = array_flip($presentIDs);
693 $gcValues = $shValues = [];
694 foreach ($input as $cid) {
695 if (isset($presentIDs[$cid])) {
696 $numContactsNotAdded++
;
700 $gcValues[] = "( $groupID, $cid, '$status' )";
701 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
705 if (!empty($gcValues)) {
706 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
707 CRM_Core_DAO
::executeQuery($cgSQL);
709 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
710 CRM_Core_DAO
::executeQuery($shSQL);
714 return ['count_added' => $numContactsAdded, 'count_not_added' => $numContactsNotAdded];
718 * Get options for a given field.
719 * @see CRM_Core_DAO::buildOptions
721 * @param string $fieldName
722 * @param string $context
723 * @see CRM_Core_DAO::buildOptionsContext
724 * @param array $props
725 * whatever is known about this dao object.
729 public static function buildOptions($fieldName, $context = NULL, $props = []) {
730 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, [], $context);
732 // Sort group list by hierarchy
733 // TODO: This will only work when api.entity is "group_contact". What about others?
734 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
735 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);