3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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) {
56 $dataExists = self
::dataExists($params);
61 $groupContact = new CRM_Contact_BAO_GroupContact();
62 $groupContact->copyValues($params);
63 CRM_Contact_BAO_SubscriptionHistory
::create($params);
64 $groupContact->save();
69 * Check if there is data to create the object.
71 * @param array $params
72 * (reference ) an assoc array of name/value pairs.
76 public static function dataExists(&$params) {
77 // return if no data present
78 if ($params['group_id'] == 0) {
86 * Given the list of params in the params array, fetch the object
87 * and store the values in the values array
89 * @param array $params
90 * Input parameters to find object.
91 * @param array $values
92 * Output values of the object.
95 * (reference) the values that could be potentially assigned to smarty
97 public static function getValues(&$params, &$values) {
101 $values['group']['data'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
106 // get the total count of groups
107 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
117 * Given an array of contact ids, add all the contacts to the group
119 * @param array $contactIds
120 * The array of contact ids to be added.
121 * @param int $groupId
122 * The id of the group.
123 * @param string $method
124 * @param string $status
125 * @param int $tracking
128 * (total, added, notAdded) count of contacts added to group
130 public static function addContactsToGroup(
137 if (empty($contactIds) ||
empty($groupId)) {
141 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
143 list($numContactsAdded, $numContactsNotAdded)
144 = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
146 // also reset the acl cache
147 $config = CRM_Core_Config
::singleton();
148 if (!$config->doNotResetCache
) {
149 CRM_ACL_BAO_Cache
::resetCache();
152 // reset the group contact cache for all group(s)
153 // if this group is being used as a smart group
154 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
156 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
158 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
162 * Given an array of contact ids, remove all the contacts from the group
164 * @param array $contactIds
165 * (reference ) the array of contact ids to be removed.
166 * @param int $groupId
167 * The id of the group.
169 * @param string $method
170 * @param string $status
171 * @param NULL $tracking
174 * (total, removed, notRemoved) count of contacts removed to group
176 public static function removeContactsFromGroup(
183 if (!is_array($contactIds)) {
184 return array(0, 0, 0);
187 if ($status == 'Removed' ||
$status == 'Deleted') {
194 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
196 $date = date('YmdHis');
197 $numContactsRemoved = 0;
198 $numContactsNotRemoved = 0;
200 $group = new CRM_Contact_DAO_Group();
201 $group->id
= $groupId;
204 foreach ($contactIds as $contactId) {
205 if ($status == 'Deleted') {
206 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
207 $dao = CRM_Core_DAO
::executeQuery($query);
208 $historyParams = array(
209 'group_id' => $groupId,
210 'contact_id' => $contactId,
214 'tracking' => $tracking,
216 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
219 $groupContact = new CRM_Contact_DAO_GroupContact();
220 $groupContact->group_id
= $groupId;
221 $groupContact->contact_id
= $contactId;
222 // check if the selected contact id already a member, or if this is
223 // an opt-out of a smart group.
224 // if not a member remove to groupContact else keep the count of contacts that are not removed
225 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
226 // remove the contact from the group
227 $numContactsRemoved++
;
230 $numContactsNotRemoved++
;
233 //now we grant the negative membership to contact if not member. CRM-3711
234 $historyParams = array(
235 'group_id' => $groupId,
236 'contact_id' => $contactId,
240 'tracking' => $tracking,
242 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
243 $groupContact->status
= $status;
244 $groupContact->save();
248 // also reset the acl cache
249 $config = CRM_Core_Config
::singleton();
250 if (!$config->doNotResetCache
) {
251 CRM_ACL_BAO_Cache
::resetCache();
254 // reset the group contact cache for all group(s)
255 // if this group is being used as a smart group
256 // @todo consider what to do here - it feels like we should either
257 // 1) just invalidate the specific group's cache(& perhaps any parents) & let cron do it's thing or
258 // possibly clear this specific groups cache, or just call opportunisticCacheFlush() - which would have the
259 // same effect as the remove call. The reservation about that is that it is no more aggressive for the group that
260 // we know is altered than for all the others, or perhaps, more the point with it's parents & groups that use it in
262 CRM_Contact_BAO_GroupContactCache
::remove();
264 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
266 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
270 * Get list of all the groups and groups for a contact.
272 * @param int $contactId
275 * @param bool $visibility
279 * this array has key-> group id and value group title
281 public static function getGroupList($contactId = 0, $visibility = FALSE) {
282 $group = new CRM_Contact_DAO_Group();
284 $select = $from = $where = '';
286 $select = 'SELECT civicrm_group.id, civicrm_group.title ';
287 $from = ' FROM civicrm_group ';
288 $where = " WHERE civicrm_group.is_active = 1 ";
290 $from .= ' , civicrm_group_contact ';
291 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
292 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
296 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
298 $groupBy = " GROUP BY civicrm_group.id";
300 $orderby = " ORDER BY civicrm_group.name";
301 $sql = $select . $from . $where . $groupBy . $orderby;
306 while ($group->fetch()) {
307 $values[$group->id
] = $group->title
;
314 * Get the list of groups for contact based on status of group membership.
316 * @param int $contactId
318 * @param string $status
319 * State of membership.
320 * @param int $numGroupContact
321 * Number of groups for a contact that should be shown.
323 * True if we are interested only in the count.
324 * @param bool $ignorePermission
325 * True if we should ignore permissions for the current user.
326 * useful in profile where permissions are limited for the user. If left
327 * at false only groups viewable by the current user are returned
328 * @param bool $onlyPublicGroups
329 * True if we want to hide system groups.
331 * @param bool $excludeHidden
333 * @param int $groupId
335 * @param bool $includeSmartGroups
336 * Include or Exclude Smart Group(s)
338 * @return array|int $values
339 * the relevant data object values for the contact or the total count when $count is TRUE
341 public static function getContactGroup(
344 $numGroupContact = NULL,
346 $ignorePermission = FALSE,
347 $onlyPublicGroups = FALSE,
348 $excludeHidden = TRUE,
350 $includeSmartGroups = FALSE
353 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
357 civicrm_group_contact.id as civicrm_group_contact_id,
358 civicrm_group.title as group_title,
359 civicrm_group.visibility as visibility,
360 civicrm_group_contact.status as status,
361 civicrm_group.id as group_id,
362 civicrm_group.is_hidden as is_hidden,
363 civicrm_subscription_history.date as date,
364 civicrm_subscription_history.method as method';
367 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
368 if (!$includeSmartGroups) {
369 $where .= " AND saved_search_id IS NULL";
371 if ($excludeHidden) {
372 $where .= " AND civicrm_group.is_hidden = 0 ";
374 $params = array(1 => array($contactId, 'Integer'));
375 if (!empty($status)) {
376 $where .= ' AND civicrm_group_contact.status = %2';
377 $params[2] = array($status, 'String');
379 if (!empty($groupId)) {
380 $where .= " AND civicrm_group.id = %3 ";
381 $params[3] = array($groupId, 'Integer');
384 'civicrm_group_contact' => 1,
385 'civicrm_group' => 1,
386 'civicrm_subscription_history' => 1,
388 $whereTables = array();
389 if ($ignorePermission) {
390 $permission = ' ( 1 ) ';
393 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
396 $from = CRM_Contact_BAO_Query
::fromClause($tables);
398 $where .= " AND $permission ";
400 if ($onlyPublicGroups) {
401 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
404 $order = $limit = '';
406 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
408 if ($numGroupContact) {
409 $limit = " LIMIT 0, $numGroupContact";
413 $sql = $select . $from . $where . $order . $limit;
416 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
420 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
422 while ($dao->fetch()) {
423 $id = $dao->civicrm_group_contact_id
;
424 $values[$id]['id'] = $id;
425 $values[$id]['group_id'] = $dao->group_id
;
426 $values[$id]['title'] = $dao->group_title
;
427 $values[$id]['visibility'] = $dao->visibility
;
428 $values[$id]['is_hidden'] = $dao->is_hidden
;
429 switch ($dao->status
) {
439 $prefix = 'pending_';
441 $values[$id][$prefix . 'date'] = $dao->date
;
442 $values[$id][$prefix . 'method'] = $dao->method
;
443 if ($status == 'Removed') {
444 $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 )";
445 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
446 if ($dateDAO->fetch()) {
447 $values[$id]['date_added'] = $dateDAO->date_added
;
456 * Returns membership details of a contact for a group.
458 * @param int $contactId
460 * @param int $groupID
461 * Id of a particular group.
462 * @param string $method
463 * If we want the subscription history details for a specific method.
468 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
469 $leftJoin = $where = $orderBy = NULL;
472 //CRM-13341 add group_id clause
474 LEFT JOIN civicrm_subscription_history
475 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
476 AND civicrm_subscription_history.group_id = {$groupID} )";
477 $where = "AND civicrm_subscription_history.method ='Email'";
478 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
482 FROM civicrm_group_contact
484 WHERE civicrm_group_contact.contact_id = %1
485 AND civicrm_group_contact.group_id = %2
491 1 => array($contactId, 'Integer'),
492 2 => array($groupID, 'Integer'),
494 $dao = CRM_Core_DAO
::executeQuery($query, $params);
500 * Method to get Group Id.
502 * @param int $groupContactID
503 * Id of a particular group.
508 public static function getGroupId($groupContactID) {
509 $dao = new CRM_Contact_DAO_GroupContact();
510 $dao->id
= $groupContactID;
512 return $dao->group_id
;
516 * Takes an associative array and creates / removes
517 * contacts from the groups
520 * @param array $params
521 * (reference ) an assoc array of name/value pairs.
522 * @param array $contactId
525 * @param bool $visibility
526 * @param string $method
528 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
529 $contactIds = array();
530 $contactIds[] = $contactId;
532 //if $visibility is true we are coming in via profile mean $method = 'Web'
533 $ignorePermission = FALSE;
535 $ignorePermission = TRUE;
539 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
540 NULL, FALSE, $ignorePermission
542 if (is_array($contactGroupList)) {
543 foreach ($contactGroupList as $key) {
544 $groupId = $key['group_id'];
545 $contactGroup[$groupId] = $groupId;
550 // get the list of all the groups
551 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
553 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
554 if (!is_array($params)) {
558 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
559 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
560 $contactGroup = array();
563 // check which values has to be add/remove contact from group
564 foreach ($allGroup as $key => $varValue) {
565 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
566 // add contact to group
567 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
569 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
570 // remove contact from group
571 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
577 * @param int $contactID
578 * @param int $groupID
582 public static function isContactInGroup($contactID, $groupID) {
583 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
584 !CRM_Utils_Rule
::positiveInteger($groupID)
590 array('group', 'IN', array($groupID), 0, 0),
591 array('contact_id', '=', $contactID, 0, 0),
593 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
595 if (!empty($contacts)) {
602 * Function merges the groups from otherContactID to mainContactID.
603 * along with subscription history
605 * @param int $mainContactId
606 * Contact id of main contact record.
607 * @param int $otherContactId
608 * Contact id of record which is going to merge.
610 * @see CRM_Dedupe_Merger::cpTables()
612 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
614 public static function mergeGroupContact($mainContactId, $otherContactId) {
616 1 => array($mainContactId, 'Integer'),
617 2 => array($otherContactId, 'Integer'),
620 // find all groups that are in otherContactID but not in mainContactID, copy them over
622 SELECT cOther.group_id
623 FROM civicrm_group_contact cOther
624 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
625 WHERE cOther.contact_id = %2
626 AND cMain.contact_id IS NULL
628 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
630 $otherGroupIDs = array();
631 while ($dao->fetch()) {
632 $otherGroupIDs[] = $dao->group_id
;
635 if (!empty($otherGroupIDs)) {
636 $otherGroupIDString = implode(',', $otherGroupIDs);
639 UPDATE civicrm_group_contact
641 WHERE contact_id = %2
642 AND group_id IN ( $otherGroupIDString )
644 CRM_Core_DAO
::executeQuery($sql, $params);
647 UPDATE civicrm_subscription_history
649 WHERE contact_id = %2
650 AND group_id IN ( $otherGroupIDString )
652 CRM_Core_DAO
::executeQuery($sql, $params);
656 SELECT cOther.group_id as group_id,
657 cOther.status as group_status
658 FROM civicrm_group_contact cMain
659 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
660 WHERE cMain.contact_id = %1
661 AND cOther.contact_id = %2
663 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
666 while ($dao->fetch()) {
667 // only copy it over if it has added status and migrate the history
668 if ($dao->group_status
== 'Added') {
669 $groupIDs[] = $dao->group_id
;
673 if (!empty($groupIDs)) {
674 $groupIDString = implode(',', $groupIDs);
677 UPDATE civicrm_group_contact
679 WHERE contact_id = %1
680 AND group_id IN ( $groupIDString )
682 CRM_Core_DAO
::executeQuery($sql, $params);
685 UPDATE civicrm_subscription_history
687 WHERE contact_id = %2
688 AND group_id IN ( $groupIDString )
690 CRM_Core_DAO
::executeQuery($sql, $params);
693 // delete all the other group contacts
696 FROM civicrm_group_contact
697 WHERE contact_id = %2
699 CRM_Core_DAO
::executeQuery($sql, $params);
703 FROM civicrm_subscription_history
704 WHERE contact_id = %2
706 CRM_Core_DAO
::executeQuery($sql, $params);
710 * Given an array of contact ids, add all the contacts to the group
712 * @param array $contactIDs
713 * The array of contact ids to be added.
714 * @param int $groupID
715 * The id of the group.
716 * @param string $method
717 * @param string $status
718 * @param NULL $tracking
721 * (total, added, notAdded) count of contacts added to group
723 public static function bulkAddContactsToGroup(
731 $numContactsAdded = 0;
732 $numContactsNotAdded = 0;
735 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
738 $subscriptioHistorySQL = "
739 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
743 $date = date('YmdHis');
745 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
746 while (!empty($contactIDs)) {
747 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
748 $contactStr = implode(',', $input);
750 // lets check their current status
752 SELECT GROUP_CONCAT(contact_id) as contactStr
753 FROM civicrm_group_contact
756 AND contact_id IN ( $contactStr )
759 1 => array($groupID, 'Integer'),
760 2 => array($status, 'String'),
763 $presentIDs = array();
764 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
766 $presentIDs = explode(',', $dao->contactStr
);
767 $presentIDs = array_flip($presentIDs);
770 $gcValues = $shValues = array();
771 foreach ($input as $cid) {
772 if (isset($presentIDs[$cid])) {
773 $numContactsNotAdded++
;
777 $gcValues[] = "( $groupID, $cid, '$status' )";
778 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
782 if (!empty($gcValues)) {
783 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
784 CRM_Core_DAO
::executeQuery($cgSQL);
786 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
787 CRM_Core_DAO
::executeQuery($shSQL);
791 return array($numContactsAdded, $numContactsNotAdded);
795 * Get options for a given field.
796 * @see CRM_Core_DAO::buildOptions
798 * @param string $fieldName
799 * @param string $context
800 * @see CRM_Core_DAO::buildOptionsContext
801 * @param array $props
802 * whatever is known about this dao object.
806 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
809 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
811 // Sort group list by hierarchy
812 // TODO: This will only work when api.entity is "group_contact". What about others?
813 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
814 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);