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
{
22 public function __construct() {
23 parent
::__construct();
27 * Takes an associative array and creates a groupContact object.
29 * the function extract all the params it needs to initialize the create a
30 * group object. the params array could contain additional unused name/value
33 * @param array $params
34 * (reference ) an assoc array of name/value pairs.
36 * @return CRM_Contact_BAO_Group
38 public static function add($params) {
39 $hook = empty($params['id']) ?
'create' : 'edit';
40 CRM_Utils_Hook
::pre($hook, 'GroupContact', CRM_Utils_Array
::value('id', $params), $params);
42 if (!self
::dataExists($params)) {
46 $groupContact = new CRM_Contact_BAO_GroupContact();
47 $groupContact->copyValues($params);
48 $groupContact->save();
50 // Lookup existing info for the sake of subscription history
51 if (!empty($params['id'])) {
52 $groupContact->find(TRUE);
53 $params = $groupContact->toArray();
55 CRM_Contact_BAO_SubscriptionHistory
::create($params);
57 CRM_Utils_Hook
::post($hook, 'GroupContact', $groupContact->id
, $groupContact);
63 * Check if there is data to create the object.
65 * @param array $params
66 * (reference ) an assoc array of name/value pairs.
70 public static function dataExists(&$params) {
71 return (!empty($params['id']) ||
(!empty($params['group_id']) && !empty($params['contact_id'])));
75 * Given the list of params in the params array, fetch the object
76 * and store the values in the values array
78 * @param array $params
79 * Input parameters to find object.
80 * @param array $values
81 * Output values of the object.
84 * (reference) the values that could be potentially assigned to smarty
86 public static function getValues(&$params, &$values) {
90 $values['group']['data'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
95 // get the total count of groups
96 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
106 * Given an array of contact ids, add all the contacts to the group
108 * @param array $contactIds
109 * The array of contact ids to be added.
110 * @param int $groupId
111 * The id of the group.
112 * @param string $method
113 * @param string $status
114 * @param int $tracking
117 * (total, added, notAdded) count of contacts added to group
119 public static function addContactsToGroup(
126 if (empty($contactIds) ||
empty($groupId)) {
130 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
132 list($numContactsAdded, $numContactsNotAdded)
133 = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
135 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
137 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
139 return [count($contactIds), $numContactsAdded, $numContactsNotAdded];
143 * Given an array of contact ids, remove all the contacts from the group
145 * @param array $contactIds
146 * (reference ) the array of contact ids to be removed.
147 * @param int $groupId
148 * The id of the group.
150 * @param string $method
151 * @param string $status
152 * @param string $tracking
155 * (total, removed, notRemoved) count of contacts removed to group
157 public static function removeContactsFromGroup(
164 if (!is_array($contactIds)) {
167 if ($status == 'Removed' ||
$status == 'Deleted') {
174 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
176 $date = date('YmdHis');
177 $numContactsRemoved = 0;
178 $numContactsNotRemoved = 0;
180 $group = new CRM_Contact_DAO_Group();
181 $group->id
= $groupId;
184 foreach ($contactIds as $contactId) {
185 if ($status == 'Deleted') {
186 $query = "DELETE FROM civicrm_group_contact WHERE contact_id = %1 AND group_id = %2";
187 $dao = CRM_Core_DAO
::executeQuery($query, [
188 1 => [$contactId, 'Positive'],
189 2 => [$groupId, 'Positive'],
192 'group_id' => $groupId,
193 'contact_id' => $contactId,
197 'tracking' => $tracking,
199 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
200 // Removing a row from civicrm_group_contact for a smart group may mean a contact
201 // Is now back in a group based on criteria so we will invalidate the cache if it is there
202 // So that accurate group cache is created next time it is needed.
203 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($groupId);
206 $groupContact = new CRM_Contact_DAO_GroupContact();
207 $groupContact->group_id
= $groupId;
208 $groupContact->contact_id
= $contactId;
209 // check if the selected contact id already a member, or if this is
210 // an opt-out of a smart group.
211 // if not a member remove to groupContact else keep the count of contacts that are not removed
212 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
213 // remove the contact from the group
214 $numContactsRemoved++
;
217 $numContactsNotRemoved++
;
220 //now we grant the negative membership to contact if not member. CRM-3711
222 'group_id' => $groupId,
223 'contact_id' => $contactId,
227 'tracking' => $tracking,
229 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
230 $groupContact->status
= $status;
231 $groupContact->save();
232 // Remove any rows from the group contact cache so it disappears straight away from smart groups.
233 CRM_Contact_BAO_GroupContactCache
::removeContact($contactId, $groupId);
237 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
239 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
241 return [count($contactIds), $numContactsRemoved, $numContactsNotRemoved];
245 * Get list of all the groups and groups for a contact.
247 * @param int $contactId
250 * @param bool $visibility
254 * this array has key-> group id and value group title
256 public static function getGroupList($contactId = 0, $visibility = FALSE) {
257 $group = new CRM_Contact_DAO_Group();
259 $select = $from = $where = '';
261 $select = 'SELECT civicrm_group.id, civicrm_group.title ';
262 $from = ' FROM civicrm_group ';
263 $where = " WHERE civicrm_group.is_active = 1 ";
265 $from .= ' , civicrm_group_contact ';
266 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
267 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
271 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
273 $groupBy = " GROUP BY civicrm_group.id";
275 $orderby = " ORDER BY civicrm_group.name";
276 $sql = $select . $from . $where . $groupBy . $orderby;
281 while ($group->fetch()) {
282 $values[$group->id
] = $group->title
;
289 * Get the list of groups for contact based on status of group membership.
291 * @param int $contactId
293 * @param string $status
294 * State of membership.
295 * @param int $numGroupContact
296 * Number of groups for a contact that should be shown.
298 * True if we are interested only in the count.
299 * @param bool $ignorePermission
300 * True if we should ignore permissions for the current user.
301 * useful in profile where permissions are limited for the user. If left
302 * at false only groups viewable by the current user are returned
303 * @param bool $onlyPublicGroups
304 * True if we want to hide system groups.
306 * @param bool $excludeHidden
308 * @param int $groupId
310 * @param bool $includeSmartGroups
311 * Include or Exclude Smart Group(s)
314 * the relevant data object values for the contact or the total count when $count is TRUE
316 public static function getContactGroup(
319 $numGroupContact = NULL,
321 $ignorePermission = FALSE,
322 $onlyPublicGroups = FALSE,
323 $excludeHidden = TRUE,
325 $includeSmartGroups = FALSE
328 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
332 civicrm_group_contact.id as civicrm_group_contact_id,
333 civicrm_group.title as group_title,
334 civicrm_group.visibility as visibility,
335 civicrm_group_contact.status as status,
336 civicrm_group.id as group_id,
337 civicrm_group.is_hidden as is_hidden,
338 civicrm_subscription_history.date as date,
339 civicrm_subscription_history.method as method';
342 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
343 if (!$includeSmartGroups) {
344 $where .= " AND saved_search_id IS NULL";
346 if ($excludeHidden) {
347 $where .= " AND civicrm_group.is_hidden = 0 ";
349 $params = [1 => [$contactId, 'Integer']];
350 if (!empty($status)) {
351 $where .= ' AND civicrm_group_contact.status = %2';
352 $params[2] = [$status, 'String'];
354 if (!empty($groupId)) {
355 $where .= " AND civicrm_group.id = %3 ";
356 $params[3] = [$groupId, 'Integer'];
359 'civicrm_group_contact' => 1,
360 'civicrm_group' => 1,
361 'civicrm_subscription_history' => 1,
364 if ($ignorePermission) {
365 $permission = ' ( 1 ) ';
368 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
371 $from = CRM_Contact_BAO_Query
::fromClause($tables);
373 $where .= " AND $permission ";
375 if ($onlyPublicGroups) {
376 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
379 $order = $limit = '';
381 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
383 if ($numGroupContact) {
384 $limit = " LIMIT 0, $numGroupContact";
388 $sql = $select . $from . $where . $order . $limit;
391 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
395 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
397 while ($dao->fetch()) {
398 $id = $dao->civicrm_group_contact_id
;
399 $values[$id]['id'] = $id;
400 $values[$id]['group_id'] = $dao->group_id
;
401 $values[$id]['title'] = $dao->group_title
;
402 $values[$id]['visibility'] = $dao->visibility
;
403 $values[$id]['is_hidden'] = $dao->is_hidden
;
404 switch ($dao->status
) {
414 $prefix = 'pending_';
416 $values[$id][$prefix . 'date'] = $dao->date
;
417 $values[$id][$prefix . 'method'] = $dao->method
;
418 if ($status == 'Removed') {
419 $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 )";
420 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
421 if ($dateDAO->fetch()) {
422 $values[$id]['date_added'] = $dateDAO->date_added
;
431 * Returns membership details of a contact for a group.
433 * @param int $contactId
435 * @param int $groupID
436 * Id of a particular group.
437 * @param string $method
438 * If we want the subscription history details for a specific method.
443 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
444 $leftJoin = $where = $orderBy = NULL;
447 //CRM-13341 add group_id clause
449 LEFT JOIN civicrm_subscription_history
450 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
451 AND civicrm_subscription_history.group_id = {$groupID} )";
452 $where = "AND civicrm_subscription_history.method ='Email'";
453 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
457 FROM civicrm_group_contact
459 WHERE civicrm_group_contact.contact_id = %1
460 AND civicrm_group_contact.group_id = %2
466 1 => [$contactId, 'Integer'],
467 2 => [$groupID, 'Integer'],
469 $dao = CRM_Core_DAO
::executeQuery($query, $params);
475 * Method to get Group Id.
477 * @param int $groupContactID
478 * Id of a particular group.
483 public static function getGroupId($groupContactID) {
484 $dao = new CRM_Contact_DAO_GroupContact();
485 $dao->id
= $groupContactID;
487 return $dao->group_id
;
491 * Takes an associative array and creates / removes
492 * contacts from the groups
495 * @param array $params
496 * (reference ) an assoc array of name/value pairs.
497 * @param array $contactId
500 * @param bool $visibility
501 * @param string $method
503 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
505 $contactIds[] = $contactId;
507 //if $visibility is true we are coming in via profile mean $method = 'Web'
508 $ignorePermission = FALSE;
510 $ignorePermission = TRUE;
514 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
515 NULL, FALSE, $ignorePermission
517 if (is_array($contactGroupList)) {
518 foreach ($contactGroupList as $key) {
519 $groupId = $key['group_id'];
520 $contactGroup[$groupId] = $groupId;
525 // get the list of all the groups
526 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
528 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
529 if (!is_array($params)) {
533 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
534 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
538 // check which values has to be add/remove contact from group
539 foreach ($allGroup as $key => $varValue) {
540 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
541 // add contact to group
542 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
544 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
545 // remove contact from group
546 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
552 * @param int $contactID
553 * @param int $groupID
557 public static function isContactInGroup($contactID, $groupID) {
558 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
559 !CRM_Utils_Rule
::positiveInteger($groupID)
565 ['group', 'IN', [$groupID], 0, 0],
566 ['contact_id', '=', $contactID, 0, 0],
568 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, ['contact_id']);
570 if (!empty($contacts)) {
577 * Function merges the groups from otherContactID to mainContactID.
578 * along with subscription history
580 * @param int $mainContactId
581 * Contact id of main contact record.
582 * @param int $otherContactId
583 * Contact id of record which is going to merge.
585 * @see CRM_Dedupe_Merger::cpTables()
587 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
589 public static function mergeGroupContact($mainContactId, $otherContactId) {
591 1 => [$mainContactId, 'Integer'],
592 2 => [$otherContactId, 'Integer'],
595 // find all groups that are in otherContactID but not in mainContactID, copy them over
597 SELECT cOther.group_id
598 FROM civicrm_group_contact cOther
599 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
600 WHERE cOther.contact_id = %2
601 AND cMain.contact_id IS NULL
603 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
606 while ($dao->fetch()) {
607 $otherGroupIDs[] = $dao->group_id
;
610 if (!empty($otherGroupIDs)) {
611 $otherGroupIDString = implode(',', $otherGroupIDs);
614 UPDATE civicrm_group_contact
616 WHERE contact_id = %2
617 AND group_id IN ( $otherGroupIDString )
619 CRM_Core_DAO
::executeQuery($sql, $params);
622 UPDATE civicrm_subscription_history
624 WHERE contact_id = %2
625 AND group_id IN ( $otherGroupIDString )
627 CRM_Core_DAO
::executeQuery($sql, $params);
631 SELECT cOther.group_id as group_id,
632 cOther.status as group_status
633 FROM civicrm_group_contact cMain
634 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
635 WHERE cMain.contact_id = %1
636 AND cOther.contact_id = %2
638 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
641 while ($dao->fetch()) {
642 // only copy it over if it has added status and migrate the history
643 if ($dao->group_status
== 'Added') {
644 $groupIDs[] = $dao->group_id
;
648 if (!empty($groupIDs)) {
649 $groupIDString = implode(',', $groupIDs);
652 UPDATE civicrm_group_contact
654 WHERE contact_id = %1
655 AND group_id IN ( $groupIDString )
657 CRM_Core_DAO
::executeQuery($sql, $params);
660 UPDATE civicrm_subscription_history
662 WHERE contact_id = %2
663 AND group_id IN ( $groupIDString )
665 CRM_Core_DAO
::executeQuery($sql, $params);
668 // delete all the other group contacts
671 FROM civicrm_group_contact
672 WHERE contact_id = %2
674 CRM_Core_DAO
::executeQuery($sql, $params);
678 FROM civicrm_subscription_history
679 WHERE contact_id = %2
681 CRM_Core_DAO
::executeQuery($sql, $params);
685 * Given an array of contact ids, add all the contacts to the group
687 * @param array $contactIDs
688 * The array of contact ids to be added.
689 * @param int $groupID
690 * The id of the group.
691 * @param string $method
692 * @param string $status
693 * @param string $tracking
696 * (total, added, notAdded) count of contacts added to group
698 public static function bulkAddContactsToGroup(
706 $numContactsAdded = 0;
707 $numContactsNotAdded = 0;
710 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
713 $subscriptioHistorySQL = "
714 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
718 $date = date('YmdHis');
720 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
721 while (!empty($contactIDs)) {
722 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
723 $contactStr = implode(',', $input);
725 // lets check their current status
727 SELECT GROUP_CONCAT(contact_id) as contactStr
728 FROM civicrm_group_contact
731 AND contact_id IN ( $contactStr )
734 1 => [$groupID, 'Integer'],
735 2 => [$status, 'String'],
739 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
741 $presentIDs = explode(',', $dao->contactStr
);
742 $presentIDs = array_flip($presentIDs);
745 $gcValues = $shValues = [];
746 foreach ($input as $cid) {
747 if (isset($presentIDs[$cid])) {
748 $numContactsNotAdded++
;
752 $gcValues[] = "( $groupID, $cid, '$status' )";
753 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
757 if (!empty($gcValues)) {
758 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
759 CRM_Core_DAO
::executeQuery($cgSQL);
761 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
762 CRM_Core_DAO
::executeQuery($shSQL);
766 return [$numContactsAdded, $numContactsNotAdded];
770 * Get options for a given field.
771 * @see CRM_Core_DAO::buildOptions
773 * @param string $fieldName
774 * @param string $context
775 * @see CRM_Core_DAO::buildOptionsContext
776 * @param array $props
777 * whatever is known about this dao object.
781 public static function buildOptions($fieldName, $context = NULL, $props = []) {
783 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $props, $context);
785 // Sort group list by hierarchy
786 // TODO: This will only work when api.entity is "group_contact". What about others?
787 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
788 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);