3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Contact_BAO_GroupContact
extends CRM_Contact_DAO_GroupContact
{
38 public function __construct() {
39 parent
::__construct();
43 * Takes an associative array and creates a groupContact object.
45 * the function extract all the params it needs to initialize the create a
46 * group object. the params array could contain additional unused name/value
49 * @param array $params
50 * (reference ) an assoc array of name/value pairs.
52 * @return CRM_Contact_BAO_Group
54 public static function add($params) {
55 $hook = empty($params['id']) ?
'create' : 'edit';
56 CRM_Utils_Hook
::pre($hook, 'GroupContact', CRM_Utils_Array
::value('id', $params), $params);
58 if (!self
::dataExists($params)) {
62 $groupContact = new CRM_Contact_BAO_GroupContact();
63 $groupContact->copyValues($params);
64 $groupContact->save();
66 // Lookup existing info for the sake of subscription history
67 if (!empty($params['id'])) {
68 $groupContact->find(TRUE);
69 $params = $groupContact->toArray();
71 CRM_Contact_BAO_SubscriptionHistory
::create($params);
73 CRM_Utils_Hook
::post($hook, 'GroupContact', $groupContact->id
, $groupContact);
79 * Check if there is data to create the object.
81 * @param array $params
82 * (reference ) an assoc array of name/value pairs.
86 public static function dataExists(&$params) {
87 return (!empty($params['id']) ||
(!empty($params['group_id']) && !empty($params['contact_id'])));
91 * Given the list of params in the params array, fetch the object
92 * and store the values in the values array
94 * @param array $params
95 * Input parameters to find object.
96 * @param array $values
97 * Output values of the object.
100 * (reference) the values that could be potentially assigned to smarty
102 public static function getValues(&$params, &$values) {
103 if (empty($params)) {
106 $values['group']['data'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
111 // get the total count of groups
112 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
122 * Given an array of contact ids, add all the contacts to the group
124 * @param array $contactIds
125 * The array of contact ids to be added.
126 * @param int $groupId
127 * The id of the group.
128 * @param string $method
129 * @param string $status
130 * @param int $tracking
133 * (total, added, notAdded) count of contacts added to group
135 public static function addContactsToGroup(
142 if (empty($contactIds) ||
empty($groupId)) {
146 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
148 list($numContactsAdded, $numContactsNotAdded)
149 = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
151 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
153 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
155 return [count($contactIds), $numContactsAdded, $numContactsNotAdded];
159 * Given an array of contact ids, remove all the contacts from the group
161 * @param array $contactIds
162 * (reference ) the array of contact ids to be removed.
163 * @param int $groupId
164 * The id of the group.
166 * @param string $method
167 * @param string $status
168 * @param string $tracking
171 * (total, removed, notRemoved) count of contacts removed to group
173 public static function removeContactsFromGroup(
180 if (!is_array($contactIds)) {
183 if ($status == 'Removed' ||
$status == 'Deleted') {
190 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
192 $date = date('YmdHis');
193 $numContactsRemoved = 0;
194 $numContactsNotRemoved = 0;
196 $group = new CRM_Contact_DAO_Group();
197 $group->id
= $groupId;
200 foreach ($contactIds as $contactId) {
201 if ($status == 'Deleted') {
202 $query = "DELETE FROM civicrm_group_contact WHERE contact_id = %1 AND group_id = %2";
203 $dao = CRM_Core_DAO
::executeQuery($query, [
204 1 => [$contactId, 'Positive'],
205 2 => [$groupId, 'Positive'],
208 'group_id' => $groupId,
209 'contact_id' => $contactId,
213 'tracking' => $tracking,
215 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
216 // Removing a row from civicrm_group_contact for a smart group may mean a contact
217 // Is now back in a group based on criteria so we will invalidate the cache if it is there
218 // So that accurate group cache is created next time it is needed.
219 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($groupId);
222 $groupContact = new CRM_Contact_DAO_GroupContact();
223 $groupContact->group_id
= $groupId;
224 $groupContact->contact_id
= $contactId;
225 // check if the selected contact id already a member, or if this is
226 // an opt-out of a smart group.
227 // if not a member remove to groupContact else keep the count of contacts that are not removed
228 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
229 // remove the contact from the group
230 $numContactsRemoved++
;
233 $numContactsNotRemoved++
;
236 //now we grant the negative membership to contact if not member. CRM-3711
238 'group_id' => $groupId,
239 'contact_id' => $contactId,
243 'tracking' => $tracking,
245 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
246 $groupContact->status
= $status;
247 $groupContact->save();
248 // Remove any rows from the group contact cache so it disappears straight away from smart groups.
249 CRM_Contact_BAO_GroupContactCache
::removeContact($contactId, $groupId);
253 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
255 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
257 return [count($contactIds), $numContactsRemoved, $numContactsNotRemoved];
261 * Get list of all the groups and groups for a contact.
263 * @param int $contactId
266 * @param bool $visibility
270 * this array has key-> group id and value group title
272 public static function getGroupList($contactId = 0, $visibility = FALSE) {
273 $group = new CRM_Contact_DAO_Group();
275 $select = $from = $where = '';
277 $select = 'SELECT civicrm_group.id, civicrm_group.title ';
278 $from = ' FROM civicrm_group ';
279 $where = " WHERE civicrm_group.is_active = 1 ";
281 $from .= ' , civicrm_group_contact ';
282 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
283 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
287 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
289 $groupBy = " GROUP BY civicrm_group.id";
291 $orderby = " ORDER BY civicrm_group.name";
292 $sql = $select . $from . $where . $groupBy . $orderby;
297 while ($group->fetch()) {
298 $values[$group->id
] = $group->title
;
305 * Get the list of groups for contact based on status of group membership.
307 * @param int $contactId
309 * @param string $status
310 * State of membership.
311 * @param int $numGroupContact
312 * Number of groups for a contact that should be shown.
314 * True if we are interested only in the count.
315 * @param bool $ignorePermission
316 * True if we should ignore permissions for the current user.
317 * useful in profile where permissions are limited for the user. If left
318 * at false only groups viewable by the current user are returned
319 * @param bool $onlyPublicGroups
320 * True if we want to hide system groups.
322 * @param bool $excludeHidden
324 * @param int $groupId
326 * @param bool $includeSmartGroups
327 * Include or Exclude Smart Group(s)
330 * the relevant data object values for the contact or the total count when $count is TRUE
332 public static function getContactGroup(
335 $numGroupContact = NULL,
337 $ignorePermission = FALSE,
338 $onlyPublicGroups = FALSE,
339 $excludeHidden = TRUE,
341 $includeSmartGroups = FALSE
344 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
348 civicrm_group_contact.id as civicrm_group_contact_id,
349 civicrm_group.title as group_title,
350 civicrm_group.visibility as visibility,
351 civicrm_group_contact.status as status,
352 civicrm_group.id as group_id,
353 civicrm_group.is_hidden as is_hidden,
354 civicrm_subscription_history.date as date,
355 civicrm_subscription_history.method as method';
358 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
359 if (!$includeSmartGroups) {
360 $where .= " AND saved_search_id IS NULL";
362 if ($excludeHidden) {
363 $where .= " AND civicrm_group.is_hidden = 0 ";
365 $params = [1 => [$contactId, 'Integer']];
366 if (!empty($status)) {
367 $where .= ' AND civicrm_group_contact.status = %2';
368 $params[2] = [$status, 'String'];
370 if (!empty($groupId)) {
371 $where .= " AND civicrm_group.id = %3 ";
372 $params[3] = [$groupId, 'Integer'];
375 'civicrm_group_contact' => 1,
376 'civicrm_group' => 1,
377 'civicrm_subscription_history' => 1,
380 if ($ignorePermission) {
381 $permission = ' ( 1 ) ';
384 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
387 $from = CRM_Contact_BAO_Query
::fromClause($tables);
389 $where .= " AND $permission ";
391 if ($onlyPublicGroups) {
392 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
395 $order = $limit = '';
397 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
399 if ($numGroupContact) {
400 $limit = " LIMIT 0, $numGroupContact";
404 $sql = $select . $from . $where . $order . $limit;
407 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
411 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
413 while ($dao->fetch()) {
414 $id = $dao->civicrm_group_contact_id
;
415 $values[$id]['id'] = $id;
416 $values[$id]['group_id'] = $dao->group_id
;
417 $values[$id]['title'] = $dao->group_title
;
418 $values[$id]['visibility'] = $dao->visibility
;
419 $values[$id]['is_hidden'] = $dao->is_hidden
;
420 switch ($dao->status
) {
430 $prefix = 'pending_';
432 $values[$id][$prefix . 'date'] = $dao->date
;
433 $values[$id][$prefix . 'method'] = $dao->method
;
434 if ($status == 'Removed') {
435 $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 )";
436 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
437 if ($dateDAO->fetch()) {
438 $values[$id]['date_added'] = $dateDAO->date_added
;
447 * Returns membership details of a contact for a group.
449 * @param int $contactId
451 * @param int $groupID
452 * Id of a particular group.
453 * @param string $method
454 * If we want the subscription history details for a specific method.
459 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
460 $leftJoin = $where = $orderBy = NULL;
463 //CRM-13341 add group_id clause
465 LEFT JOIN civicrm_subscription_history
466 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
467 AND civicrm_subscription_history.group_id = {$groupID} )";
468 $where = "AND civicrm_subscription_history.method ='Email'";
469 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
473 FROM civicrm_group_contact
475 WHERE civicrm_group_contact.contact_id = %1
476 AND civicrm_group_contact.group_id = %2
482 1 => [$contactId, 'Integer'],
483 2 => [$groupID, 'Integer'],
485 $dao = CRM_Core_DAO
::executeQuery($query, $params);
491 * Method to get Group Id.
493 * @param int $groupContactID
494 * Id of a particular group.
499 public static function getGroupId($groupContactID) {
500 $dao = new CRM_Contact_DAO_GroupContact();
501 $dao->id
= $groupContactID;
503 return $dao->group_id
;
507 * Takes an associative array and creates / removes
508 * contacts from the groups
511 * @param array $params
512 * (reference ) an assoc array of name/value pairs.
513 * @param array $contactId
516 * @param bool $visibility
517 * @param string $method
519 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
521 $contactIds[] = $contactId;
523 //if $visibility is true we are coming in via profile mean $method = 'Web'
524 $ignorePermission = FALSE;
526 $ignorePermission = TRUE;
530 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
531 NULL, FALSE, $ignorePermission
533 if (is_array($contactGroupList)) {
534 foreach ($contactGroupList as $key) {
535 $groupId = $key['group_id'];
536 $contactGroup[$groupId] = $groupId;
541 // get the list of all the groups
542 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
544 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
545 if (!is_array($params)) {
549 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
550 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
554 // check which values has to be add/remove contact from group
555 foreach ($allGroup as $key => $varValue) {
556 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
557 // add contact to group
558 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
560 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
561 // remove contact from group
562 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
568 * @param int $contactID
569 * @param int $groupID
573 public static function isContactInGroup($contactID, $groupID) {
574 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
575 !CRM_Utils_Rule
::positiveInteger($groupID)
581 ['group', 'IN', [$groupID], 0, 0],
582 ['contact_id', '=', $contactID, 0, 0],
584 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, ['contact_id']);
586 if (!empty($contacts)) {
593 * Function merges the groups from otherContactID to mainContactID.
594 * along with subscription history
596 * @param int $mainContactId
597 * Contact id of main contact record.
598 * @param int $otherContactId
599 * Contact id of record which is going to merge.
601 * @see CRM_Dedupe_Merger::cpTables()
603 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
605 public static function mergeGroupContact($mainContactId, $otherContactId) {
607 1 => [$mainContactId, 'Integer'],
608 2 => [$otherContactId, 'Integer'],
611 // find all groups that are in otherContactID but not in mainContactID, copy them over
613 SELECT cOther.group_id
614 FROM civicrm_group_contact cOther
615 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
616 WHERE cOther.contact_id = %2
617 AND cMain.contact_id IS NULL
619 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
622 while ($dao->fetch()) {
623 $otherGroupIDs[] = $dao->group_id
;
626 if (!empty($otherGroupIDs)) {
627 $otherGroupIDString = implode(',', $otherGroupIDs);
630 UPDATE civicrm_group_contact
632 WHERE contact_id = %2
633 AND group_id IN ( $otherGroupIDString )
635 CRM_Core_DAO
::executeQuery($sql, $params);
638 UPDATE civicrm_subscription_history
640 WHERE contact_id = %2
641 AND group_id IN ( $otherGroupIDString )
643 CRM_Core_DAO
::executeQuery($sql, $params);
647 SELECT cOther.group_id as group_id,
648 cOther.status as group_status
649 FROM civicrm_group_contact cMain
650 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
651 WHERE cMain.contact_id = %1
652 AND cOther.contact_id = %2
654 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
657 while ($dao->fetch()) {
658 // only copy it over if it has added status and migrate the history
659 if ($dao->group_status
== 'Added') {
660 $groupIDs[] = $dao->group_id
;
664 if (!empty($groupIDs)) {
665 $groupIDString = implode(',', $groupIDs);
668 UPDATE civicrm_group_contact
670 WHERE contact_id = %1
671 AND group_id IN ( $groupIDString )
673 CRM_Core_DAO
::executeQuery($sql, $params);
676 UPDATE civicrm_subscription_history
678 WHERE contact_id = %2
679 AND group_id IN ( $groupIDString )
681 CRM_Core_DAO
::executeQuery($sql, $params);
684 // delete all the other group contacts
687 FROM civicrm_group_contact
688 WHERE contact_id = %2
690 CRM_Core_DAO
::executeQuery($sql, $params);
694 FROM civicrm_subscription_history
695 WHERE contact_id = %2
697 CRM_Core_DAO
::executeQuery($sql, $params);
701 * Given an array of contact ids, add all the contacts to the group
703 * @param array $contactIDs
704 * The array of contact ids to be added.
705 * @param int $groupID
706 * The id of the group.
707 * @param string $method
708 * @param string $status
709 * @param string $tracking
712 * (total, added, notAdded) count of contacts added to group
714 public static function bulkAddContactsToGroup(
722 $numContactsAdded = 0;
723 $numContactsNotAdded = 0;
726 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
729 $subscriptioHistorySQL = "
730 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
734 $date = date('YmdHis');
736 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
737 while (!empty($contactIDs)) {
738 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
739 $contactStr = implode(',', $input);
741 // lets check their current status
743 SELECT GROUP_CONCAT(contact_id) as contactStr
744 FROM civicrm_group_contact
747 AND contact_id IN ( $contactStr )
750 1 => [$groupID, 'Integer'],
751 2 => [$status, 'String'],
755 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
757 $presentIDs = explode(',', $dao->contactStr
);
758 $presentIDs = array_flip($presentIDs);
761 $gcValues = $shValues = [];
762 foreach ($input as $cid) {
763 if (isset($presentIDs[$cid])) {
764 $numContactsNotAdded++
;
768 $gcValues[] = "( $groupID, $cid, '$status' )";
769 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
773 if (!empty($gcValues)) {
774 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
775 CRM_Core_DAO
::executeQuery($cgSQL);
777 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
778 CRM_Core_DAO
::executeQuery($shSQL);
782 return [$numContactsAdded, $numContactsNotAdded];
786 * Get options for a given field.
787 * @see CRM_Core_DAO::buildOptions
789 * @param string $fieldName
790 * @param string $context
791 * @see CRM_Core_DAO::buildOptionsContext
792 * @param array $props
793 * whatever is known about this dao object.
797 public static function buildOptions($fieldName, $context = NULL, $props = []) {
799 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $props, $context);
801 // Sort group list by hierarchy
802 // TODO: This will only work when api.entity is "group_contact". What about others?
803 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
804 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);