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 $result = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
133 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($groupId);
134 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
136 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
138 return [count($contactIds), $result['count_added'], $result['count_not_added']];
142 * Given an array of contact ids, remove all the contacts from the group
144 * @param array $contactIds
145 * (reference ) the array of contact ids to be removed.
146 * @param int $groupId
147 * The id of the group.
149 * @param string $method
150 * @param string $status
151 * @param string $tracking
154 * (total, removed, notRemoved) count of contacts removed to group
156 public static function removeContactsFromGroup(
163 if (!is_array($contactIds)) {
166 if ($status == 'Removed' ||
$status == 'Deleted') {
173 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
175 $date = date('YmdHis');
176 $numContactsRemoved = 0;
177 $numContactsNotRemoved = 0;
179 $group = new CRM_Contact_DAO_Group();
180 $group->id
= $groupId;
183 foreach ($contactIds as $contactId) {
184 if ($status == 'Deleted') {
185 $query = "DELETE FROM civicrm_group_contact WHERE contact_id = %1 AND group_id = %2";
186 $dao = CRM_Core_DAO
::executeQuery($query, [
187 1 => [$contactId, 'Positive'],
188 2 => [$groupId, 'Positive'],
191 'group_id' => $groupId,
192 'contact_id' => $contactId,
196 'tracking' => $tracking,
198 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
199 // Removing a row from civicrm_group_contact for a smart group may mean a contact
200 // Is now back in a group based on criteria so we will invalidate the cache if it is there
201 // So that accurate group cache is created next time it is needed.
202 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($groupId);
205 $groupContact = new CRM_Contact_DAO_GroupContact();
206 $groupContact->group_id
= $groupId;
207 $groupContact->contact_id
= $contactId;
208 // check if the selected contact id already a member, or if this is
209 // an opt-out of a smart group.
210 // if not a member remove to groupContact else keep the count of contacts that are not removed
211 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
212 // remove the contact from the group
213 $numContactsRemoved++
;
216 $numContactsNotRemoved++
;
219 //now we grant the negative membership to contact if not member. CRM-3711
221 'group_id' => $groupId,
222 'contact_id' => $contactId,
226 'tracking' => $tracking,
228 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
229 $groupContact->status
= $status;
230 $groupContact->save();
231 // Remove any rows from the group contact cache so it disappears straight away from smart groups.
232 CRM_Contact_BAO_GroupContactCache
::removeContact($contactId, $groupId);
236 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
238 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
240 return [count($contactIds), $numContactsRemoved, $numContactsNotRemoved];
244 * Get list of all the groups and groups for a contact.
246 * @param int $contactId
249 * @param bool $visibility
253 * this array has key-> group id and value group title
255 public static function getGroupList($contactId = 0, $visibility = FALSE) {
256 $select = 'SELECT civicrm_group.id, civicrm_group.title ';
257 $from = ' FROM civicrm_group ';
258 $where = " WHERE civicrm_group.is_active = 1 ";
260 $from .= ' , civicrm_group_contact ';
261 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
262 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
266 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
268 $groupBy = " GROUP BY civicrm_group.id";
270 $orderby = " ORDER BY civicrm_group.name";
271 $sql = $select . $from . $where . $groupBy . $orderby;
273 $group = CRM_Core_DAO
::executeQuery($sql);
276 while ($group->fetch()) {
277 $values[$group->id
] = $group->title
;
284 * Get the list of groups for contact based on status of group membership.
286 * @param int $contactId
288 * @param string $status
289 * State of membership.
290 * @param int $numGroupContact
291 * Number of groups for a contact that should be shown.
293 * True if we are interested only in the count.
294 * @param bool $ignorePermission
295 * True if we should ignore permissions for the current user.
296 * useful in profile where permissions are limited for the user. If left
297 * at false only groups viewable by the current user are returned
298 * @param bool $onlyPublicGroups
299 * True if we want to hide system groups.
301 * @param bool $excludeHidden
303 * @param int $groupId
305 * @param bool $includeSmartGroups
306 * Include or Exclude Smart Group(s)
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
323 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
327 civicrm_group_contact.id as civicrm_group_contact_id,
328 civicrm_group.title as group_title,
329 civicrm_group.visibility as visibility,
330 civicrm_group_contact.status as status,
331 civicrm_group.id as group_id,
332 civicrm_group.is_hidden as is_hidden,
333 civicrm_subscription_history.date as date,
334 civicrm_subscription_history.method as method';
337 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
338 if (!$includeSmartGroups) {
339 $where .= " AND saved_search_id IS NULL";
341 if ($excludeHidden) {
342 $where .= " AND civicrm_group.is_hidden = 0 ";
344 $params = [1 => [$contactId, 'Integer']];
345 if (!empty($status)) {
346 $where .= ' AND civicrm_group_contact.status = %2';
347 $params[2] = [$status, 'String'];
349 if (!empty($groupId)) {
350 $where .= " AND civicrm_group.id = %3 ";
351 $params[3] = [$groupId, 'Integer'];
354 'civicrm_group_contact' => 1,
355 'civicrm_group' => 1,
356 'civicrm_subscription_history' => 1,
359 if ($ignorePermission) {
360 $permission = ' ( 1 ) ';
363 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
366 $from = CRM_Contact_BAO_Query
::fromClause($tables);
368 $where .= " AND $permission ";
370 if ($onlyPublicGroups) {
371 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
374 $order = $limit = '';
376 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
378 if ($numGroupContact) {
379 $limit = " LIMIT 0, $numGroupContact";
383 $sql = $select . $from . $where . $order . $limit;
386 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
390 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
392 while ($dao->fetch()) {
393 $id = $dao->civicrm_group_contact_id
;
394 $values[$id]['id'] = $id;
395 $values[$id]['group_id'] = $dao->group_id
;
396 $values[$id]['title'] = $dao->group_title
;
397 $values[$id]['visibility'] = $dao->visibility
;
398 $values[$id]['is_hidden'] = $dao->is_hidden
;
399 switch ($dao->status
) {
409 $prefix = 'pending_';
411 $values[$id][$prefix . 'date'] = $dao->date
;
412 $values[$id][$prefix . 'method'] = $dao->method
;
413 if ($status == 'Removed') {
414 $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 )";
415 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
416 if ($dateDAO->fetch()) {
417 $values[$id]['date_added'] = $dateDAO->date_added
;
426 * Returns membership details of a contact for a group.
428 * @param int $contactId
430 * @param int $groupID
431 * Id of a particular group.
432 * @param string $method
433 * If we want the subscription history details for a specific method.
438 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
439 $leftJoin = $where = $orderBy = NULL;
442 //CRM-13341 add group_id clause
444 LEFT JOIN civicrm_subscription_history
445 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
446 AND civicrm_subscription_history.group_id = {$groupID} )";
447 $where = "AND civicrm_subscription_history.method ='Email'";
448 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
452 FROM civicrm_group_contact
454 WHERE civicrm_group_contact.contact_id = %1
455 AND civicrm_group_contact.group_id = %2
461 1 => [$contactId, 'Integer'],
462 2 => [$groupID, 'Integer'],
464 $dao = CRM_Core_DAO
::executeQuery($query, $params);
470 * Method to get Group Id.
472 * @param int $groupContactID
473 * Id of a particular group.
478 public static function getGroupId($groupContactID) {
479 $dao = new CRM_Contact_DAO_GroupContact();
480 $dao->id
= $groupContactID;
482 return $dao->group_id
;
486 * Creates / removes contacts from the groups
488 * FIXME: Nonstandard create function; only called from CRM_Contact_BAO_Contact::createProfileContact
490 * @param array $params
492 * @param int $contactId
495 * @param bool $ignorePermission
496 * if ignorePermission is true we are coming in via profile mean $method = 'Web'
498 * @param string $method
500 public static function create($params, $contactId, $ignorePermission = FALSE, $method = 'Admin') {
501 $contactIds = [$contactId];
505 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
506 NULL, FALSE, $ignorePermission
508 if (is_array($contactGroupList)) {
509 foreach ($contactGroupList as $key) {
510 $groupId = $key['group_id'];
511 $contactGroup[$groupId] = $groupId;
516 // get the list of all the groups
517 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $ignorePermission);
519 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
520 if (!is_array($params)) {
524 // check which values has to be add/remove contact from group
525 foreach ($allGroup as $key => $varValue) {
526 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
527 // add contact to group
528 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
530 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
531 // remove contact from group
532 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
538 * @param int $contactID
539 * @param int $groupID
543 public static function isContactInGroup($contactID, $groupID) {
544 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
545 !CRM_Utils_Rule
::positiveInteger($groupID)
551 ['group', 'IN', [$groupID], 0, 0],
552 ['contact_id', '=', $contactID, 0, 0],
554 [$contacts] = CRM_Contact_BAO_Query
::apiQuery($params, ['contact_id']);
556 if (!empty($contacts)) {
563 * Function merges the groups from otherContactID to mainContactID.
564 * along with subscription history
566 * @param int $mainContactId
567 * Contact id of main contact record.
568 * @param int $otherContactId
569 * Contact id of record which is going to merge.
571 * @see CRM_Dedupe_Merger::cpTables()
573 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
575 public static function mergeGroupContact($mainContactId, $otherContactId) {
577 1 => [$mainContactId, 'Integer'],
578 2 => [$otherContactId, 'Integer'],
581 // find all groups that are in otherContactID but not in mainContactID, copy them over
583 SELECT cOther.group_id
584 FROM civicrm_group_contact cOther
585 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
586 WHERE cOther.contact_id = %2
587 AND cMain.contact_id IS NULL
589 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
592 while ($dao->fetch()) {
593 $otherGroupIDs[] = $dao->group_id
;
596 if (!empty($otherGroupIDs)) {
597 $otherGroupIDString = implode(',', $otherGroupIDs);
600 UPDATE civicrm_group_contact
602 WHERE contact_id = %2
603 AND group_id IN ( $otherGroupIDString )
605 CRM_Core_DAO
::executeQuery($sql, $params);
608 UPDATE civicrm_subscription_history
610 WHERE contact_id = %2
611 AND group_id IN ( $otherGroupIDString )
613 CRM_Core_DAO
::executeQuery($sql, $params);
617 SELECT cOther.group_id as group_id,
618 cOther.status as group_status
619 FROM civicrm_group_contact cMain
620 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
621 WHERE cMain.contact_id = %1
622 AND cOther.contact_id = %2
624 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
627 while ($dao->fetch()) {
628 // only copy it over if it has added status and migrate the history
629 if ($dao->group_status
== 'Added') {
630 $groupIDs[] = $dao->group_id
;
634 if (!empty($groupIDs)) {
635 $groupIDString = implode(',', $groupIDs);
638 UPDATE civicrm_group_contact
640 WHERE contact_id = %1
641 AND group_id IN ( $groupIDString )
643 CRM_Core_DAO
::executeQuery($sql, $params);
646 UPDATE civicrm_subscription_history
648 WHERE contact_id = %2
649 AND group_id IN ( $groupIDString )
651 CRM_Core_DAO
::executeQuery($sql, $params);
654 // delete all the other group contacts
657 FROM civicrm_group_contact
658 WHERE contact_id = %2
660 CRM_Core_DAO
::executeQuery($sql, $params);
664 FROM civicrm_subscription_history
665 WHERE contact_id = %2
667 CRM_Core_DAO
::executeQuery($sql, $params);
671 * Given an array of contact ids, add all the contacts to the group
673 * @param array $contactIDs
674 * The array of contact ids to be added.
675 * @param int $groupID
676 * The id of the group.
677 * @param string $method
678 * @param string $status
679 * @param string $tracking
682 * (total, added, notAdded) count of contacts added to group
684 public static function bulkAddContactsToGroup(
692 $numContactsAdded = 0;
693 $numContactsNotAdded = 0;
696 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
699 $subscriptioHistorySQL = "
700 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
704 $date = date('YmdHis');
706 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
707 while (!empty($contactIDs)) {
708 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
709 $contactStr = implode(',', $input);
711 // lets check their current status
713 SELECT GROUP_CONCAT(contact_id) as contactStr
714 FROM civicrm_group_contact
717 AND contact_id IN ( $contactStr )
720 1 => [$groupID, 'Integer'],
721 2 => [$status, 'String'],
725 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
727 $presentIDs = explode(',', $dao->contactStr
);
728 $presentIDs = array_flip($presentIDs);
731 $gcValues = $shValues = [];
732 foreach ($input as $cid) {
733 if (isset($presentIDs[$cid])) {
734 $numContactsNotAdded++
;
738 $gcValues[] = "( $groupID, $cid, '$status' )";
739 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
743 if (!empty($gcValues)) {
744 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
745 CRM_Core_DAO
::executeQuery($cgSQL);
747 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
748 CRM_Core_DAO
::executeQuery($shSQL);
752 return ['count_added' => $numContactsAdded, 'count_not_added' => $numContactsNotAdded];
756 * Get options for a given field.
757 * @see CRM_Core_DAO::buildOptions
759 * @param string $fieldName
760 * @param string $context
761 * @see CRM_Core_DAO::buildOptionsContext
762 * @param array $props
763 * whatever is known about this dao object.
767 public static function buildOptions($fieldName, $context = NULL, $props = []) {
768 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, [], $context);
770 // Sort group list by hierarchy
771 // TODO: This will only work when api.entity is "group_contact". What about others?
772 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
773 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);