3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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(
138 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
140 list($numContactsAdded, $numContactsNotAdded)
141 = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
143 // also reset the acl cache
144 $config = CRM_Core_Config
::singleton();
145 if (!$config->doNotResetCache
) {
146 CRM_ACL_BAO_Cache
::resetCache();
149 // reset the group contact cache for all group(s)
150 // if this group is being used as a smart group
151 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
153 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
155 return array(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 NULL $tracking
171 * (total, removed, notRemoved) count of contacts removed to group
173 public static function removeContactsFromGroup(
180 if (!is_array($contactIds)) {
181 return array(0, 0, 0);
184 if ($status == 'Removed' ||
$status == 'Deleted') {
191 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
193 $date = date('YmdHis');
194 $numContactsRemoved = 0;
195 $numContactsNotRemoved = 0;
197 $group = new CRM_Contact_DAO_Group();
198 $group->id
= $groupId;
201 foreach ($contactIds as $contactId) {
202 if ($status == 'Deleted') {
203 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
204 $dao = CRM_Core_DAO
::executeQuery($query);
205 $historyParams = array(
206 'group_id' => $groupId,
207 'contact_id' => $contactId,
211 'tracking' => $tracking,
213 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
216 $groupContact = new CRM_Contact_DAO_GroupContact();
217 $groupContact->group_id
= $groupId;
218 $groupContact->contact_id
= $contactId;
219 // check if the selected contact id already a member, or if this is
220 // an opt-out of a smart group.
221 // if not a member remove to groupContact else keep the count of contacts that are not removed
222 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
223 // remove the contact from the group
224 $numContactsRemoved++
;
227 $numContactsNotRemoved++
;
230 //now we grant the negative membership to contact if not member. CRM-3711
231 $historyParams = array(
232 'group_id' => $groupId,
233 'contact_id' => $contactId,
237 'tracking' => $tracking,
239 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
240 $groupContact->status
= $status;
241 $groupContact->save();
245 // also reset the acl cache
246 $config = CRM_Core_Config
::singleton();
247 if (!$config->doNotResetCache
) {
248 CRM_ACL_BAO_Cache
::resetCache();
251 // reset the group contact cache for all group(s)
252 // if this group is being used as a smart group
253 // @todo consider what to do here - it feels like we should either
254 // 1) just invalidate the specific group's cache(& perhaps any parents) & let cron do it's thing or
255 // possibly clear this specific groups cache, or just call opportunisticCacheFlush() - which would have the
256 // same effect as the remove call. The reservation about that is that it is no more aggressive for the group that
257 // we know is altered than for all the others, or perhaps, more the point with it's parents & groups that use it in
259 CRM_Contact_BAO_GroupContactCache
::remove();
261 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
263 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
267 * Get list of all the groups and groups for a contact.
269 * @param int $contactId
272 * @param bool $visibility
276 * this array has key-> group id and value group title
278 public static function getGroupList($contactId = 0, $visibility = FALSE) {
279 $group = new CRM_Contact_DAO_Group();
281 $select = $from = $where = '';
283 $select = 'SELECT civicrm_group.id, civicrm_group.title ';
284 $from = ' FROM civicrm_group ';
285 $where = " WHERE civicrm_group.is_active = 1 ";
287 $from .= ' , civicrm_group_contact ';
288 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
289 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
293 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
295 $groupBy = " GROUP BY civicrm_group.id";
297 $orderby = " ORDER BY civicrm_group.name";
298 $sql = $select . $from . $where . $groupBy . $orderby;
303 while ($group->fetch()) {
304 $values[$group->id
] = $group->title
;
311 * Get the list of groups for contact based on status of group membership.
313 * @param int $contactId
315 * @param string $status
316 * State of membership.
317 * @param int $numGroupContact
318 * Number of groups for a contact that should be shown.
320 * True if we are interested only in the count.
321 * @param bool $ignorePermission
322 * True if we should ignore permissions for the current user.
323 * useful in profile where permissions are limited for the user. If left
324 * at false only groups viewable by the current user are returned
325 * @param bool $onlyPublicGroups
326 * True if we want to hide system groups.
328 * @param bool $excludeHidden
330 * @param int $groupId
332 * @return array|int $values
333 * the relevant data object values for the contact or the total count when $count is TRUE
335 public static function getContactGroup(
338 $numGroupContact = NULL,
340 $ignorePermission = FALSE,
341 $onlyPublicGroups = FALSE,
342 $excludeHidden = TRUE,
346 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
350 civicrm_group_contact.id as civicrm_group_contact_id,
351 civicrm_group.title as group_title,
352 civicrm_group.visibility as visibility,
353 civicrm_group_contact.status as status,
354 civicrm_group.id as group_id,
355 civicrm_group.is_hidden as is_hidden,
356 civicrm_subscription_history.date as date,
357 civicrm_subscription_history.method as method';
360 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1 AND saved_search_id IS NULL";
362 if ($excludeHidden) {
363 $where .= " AND civicrm_group.is_hidden = 0 ";
366 $params = array(1 => array($contactId, 'Integer'));
367 if (!empty($status)) {
368 $where .= ' AND civicrm_group_contact.status = %2';
369 $params[2] = array($status, 'String');
371 if (!empty($groupId)) {
372 $where .= " AND civicrm_group.id = %3 ";
373 $params[3] = array($groupId, 'Integer');
376 'civicrm_group_contact' => 1,
377 'civicrm_group' => 1,
378 'civicrm_subscription_history' => 1,
380 $whereTables = array();
381 if ($ignorePermission) {
382 $permission = ' ( 1 ) ';
385 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
388 $from = CRM_Contact_BAO_Query
::fromClause($tables);
390 $where .= " AND $permission ";
392 if ($onlyPublicGroups) {
393 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
396 $order = $limit = '';
398 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
400 if ($numGroupContact) {
401 $limit = " LIMIT 0, $numGroupContact";
405 $sql = $select . $from . $where . $order . $limit;
408 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
412 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
414 while ($dao->fetch()) {
415 $id = $dao->civicrm_group_contact_id
;
416 $values[$id]['id'] = $id;
417 $values[$id]['group_id'] = $dao->group_id
;
418 $values[$id]['title'] = $dao->group_title
;
419 $values[$id]['visibility'] = $dao->visibility
;
420 $values[$id]['is_hidden'] = $dao->is_hidden
;
421 switch ($dao->status
) {
431 $prefix = 'pending_';
433 $values[$id][$prefix . 'date'] = $dao->date
;
434 $values[$id][$prefix . 'method'] = $dao->method
;
435 if ($status == 'Removed') {
436 $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 )";
437 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
438 if ($dateDAO->fetch()) {
439 $values[$id]['date_added'] = $dateDAO->date_added
;
448 * Returns membership details of a contact for a group.
450 * @param int $contactId
452 * @param int $groupID
453 * Id of a particular group.
454 * @param string $method
455 * If we want the subscription history details for a specific method.
460 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
461 $leftJoin = $where = $orderBy = NULL;
464 //CRM-13341 add group_id clause
466 LEFT JOIN civicrm_subscription_history
467 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
468 AND civicrm_subscription_history.group_id = {$groupID} )";
469 $where = "AND civicrm_subscription_history.method ='Email'";
470 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
474 FROM civicrm_group_contact
476 WHERE civicrm_group_contact.contact_id = %1
477 AND civicrm_group_contact.group_id = %2
483 1 => array($contactId, 'Integer'),
484 2 => array($groupID, 'Integer'),
486 $dao = CRM_Core_DAO
::executeQuery($query, $params);
492 * Method to get Group Id.
494 * @param int $groupContactID
495 * Id of a particular group.
500 public static function getGroupId($groupContactID) {
501 $dao = new CRM_Contact_DAO_GroupContact();
502 $dao->id
= $groupContactID;
504 return $dao->group_id
;
508 * Takes an associative array and creates / removes
509 * contacts from the groups
512 * @param array $params
513 * (reference ) an assoc array of name/value pairs.
514 * @param array $contactId
517 * @param bool $visibility
518 * @param string $method
520 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
521 $contactIds = array();
522 $contactIds[] = $contactId;
524 //if $visibility is true we are coming in via profile mean $method = 'Web'
525 $ignorePermission = FALSE;
527 $ignorePermission = TRUE;
531 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
532 NULL, FALSE, $ignorePermission
534 if (is_array($contactGroupList)) {
535 foreach ($contactGroupList as $key) {
536 $groupId = $key['group_id'];
537 $contactGroup[$groupId] = $groupId;
542 // get the list of all the groups
543 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
545 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
546 if (!is_array($params)) {
550 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
551 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
552 $contactGroup = array();
555 // check which values has to be add/remove contact from group
556 foreach ($allGroup as $key => $varValue) {
557 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
558 // add contact to group
559 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
561 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
562 // remove contact from group
563 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
569 * @param int $contactID
570 * @param int $groupID
574 public static function isContactInGroup($contactID, $groupID) {
575 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
576 !CRM_Utils_Rule
::positiveInteger($groupID)
582 array('group', 'IN', array($groupID), 0, 0),
583 array('contact_id', '=', $contactID, 0, 0),
585 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
587 if (!empty($contacts)) {
594 * Function merges the groups from otherContactID to mainContactID.
595 * along with subscription history
597 * @param int $mainContactId
598 * Contact id of main contact record.
599 * @param int $otherContactId
600 * Contact id of record which is going to merge.
602 * @see CRM_Dedupe_Merger::cpTables()
604 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
606 public static function mergeGroupContact($mainContactId, $otherContactId) {
608 1 => array($mainContactId, 'Integer'),
609 2 => array($otherContactId, 'Integer'),
612 // find all groups that are in otherContactID but not in mainContactID, copy them over
614 SELECT cOther.group_id
615 FROM civicrm_group_contact cOther
616 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
617 WHERE cOther.contact_id = %2
618 AND cMain.contact_id IS NULL
620 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
622 $otherGroupIDs = array();
623 while ($dao->fetch()) {
624 $otherGroupIDs[] = $dao->group_id
;
627 if (!empty($otherGroupIDs)) {
628 $otherGroupIDString = implode(',', $otherGroupIDs);
631 UPDATE civicrm_group_contact
633 WHERE contact_id = %2
634 AND group_id IN ( $otherGroupIDString )
636 CRM_Core_DAO
::executeQuery($sql, $params);
639 UPDATE civicrm_subscription_history
641 WHERE contact_id = %2
642 AND group_id IN ( $otherGroupIDString )
644 CRM_Core_DAO
::executeQuery($sql, $params);
648 SELECT cOther.group_id as group_id,
649 cOther.status as group_status
650 FROM civicrm_group_contact cMain
651 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
652 WHERE cMain.contact_id = %1
653 AND cOther.contact_id = %2
655 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
658 while ($dao->fetch()) {
659 // only copy it over if it has added status and migrate the history
660 if ($dao->group_status
== 'Added') {
661 $groupIDs[] = $dao->group_id
;
665 if (!empty($groupIDs)) {
666 $groupIDString = implode(',', $groupIDs);
669 UPDATE civicrm_group_contact
671 WHERE contact_id = %1
672 AND group_id IN ( $groupIDString )
674 CRM_Core_DAO
::executeQuery($sql, $params);
677 UPDATE civicrm_subscription_history
679 WHERE contact_id = %2
680 AND group_id IN ( $groupIDString )
682 CRM_Core_DAO
::executeQuery($sql, $params);
685 // delete all the other group contacts
688 FROM civicrm_group_contact
689 WHERE contact_id = %2
691 CRM_Core_DAO
::executeQuery($sql, $params);
695 FROM civicrm_subscription_history
696 WHERE contact_id = %2
698 CRM_Core_DAO
::executeQuery($sql, $params);
702 * Given an array of contact ids, add all the contacts to the group
704 * @param array $contactIDs
705 * The array of contact ids to be added.
706 * @param int $groupID
707 * The id of the group.
708 * @param string $method
709 * @param string $status
710 * @param NULL $tracking
713 * (total, added, notAdded) count of contacts added to group
715 public static function bulkAddContactsToGroup(
723 $numContactsAdded = 0;
724 $numContactsNotAdded = 0;
727 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
730 $subscriptioHistorySQL = "
731 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
735 $date = date('YmdHis');
737 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
738 while (!empty($contactIDs)) {
739 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
740 $contactStr = implode(',', $input);
742 // lets check their current status
744 SELECT GROUP_CONCAT(contact_id) as contactStr
745 FROM civicrm_group_contact
748 AND contact_id IN ( $contactStr )
751 1 => array($groupID, 'Integer'),
752 2 => array($status, 'String'),
755 $presentIDs = array();
756 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
758 $presentIDs = explode(',', $dao->contactStr
);
759 $presentIDs = array_flip($presentIDs);
762 $gcValues = $shValues = array();
763 foreach ($input as $cid) {
764 if (isset($presentIDs[$cid])) {
765 $numContactsNotAdded++
;
769 $gcValues[] = "( $groupID, $cid, '$status' )";
770 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
774 if (!empty($gcValues)) {
775 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
776 CRM_Core_DAO
::executeQuery($cgSQL);
778 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
779 CRM_Core_DAO
::executeQuery($shSQL);
783 return array($numContactsAdded, $numContactsNotAdded);
787 * Get options for a given field.
788 * @see CRM_Core_DAO::buildOptions
790 * @param string $fieldName
791 * @param string $context
792 * @see CRM_Core_DAO::buildOptionsContext
793 * @param array $props
794 * whatever is known about this dao object.
798 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
801 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
803 // Sort group list by hierarchy
804 // TODO: This will only work when api.entity is "group_contact". What about others?
805 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
806 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);