3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
148 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
150 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
154 * Given an array of contact ids, remove all the contacts from the group
156 * @param array $contactIds
157 * (reference ) the array of contact ids to be removed.
158 * @param int $groupId
159 * The id of the group.
161 * @param string $method
162 * @param string $status
163 * @param NULL $tracking
166 * (total, removed, notRemoved) count of contacts removed to group
168 public static function removeContactsFromGroup(
175 if (!is_array($contactIds)) {
176 return array(0, 0, 0);
179 if ($status == 'Removed' ||
$status == 'Deleted') {
186 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
188 $date = date('YmdHis');
189 $numContactsRemoved = 0;
190 $numContactsNotRemoved = 0;
192 $group = new CRM_Contact_DAO_Group();
193 $group->id
= $groupId;
196 foreach ($contactIds as $contactId) {
197 if ($status == 'Deleted') {
198 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
199 $dao = CRM_Core_DAO
::executeQuery($query);
200 $historyParams = array(
201 'group_id' => $groupId,
202 'contact_id' => $contactId,
206 'tracking' => $tracking,
208 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
211 $groupContact = new CRM_Contact_DAO_GroupContact();
212 $groupContact->group_id
= $groupId;
213 $groupContact->contact_id
= $contactId;
214 // check if the selected contact id already a member, or if this is
215 // an opt-out of a smart group.
216 // if not a member remove to groupContact else keep the count of contacts that are not removed
217 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
218 // remove the contact from the group
219 $numContactsRemoved++
;
222 $numContactsNotRemoved++
;
225 //now we grant the negative membership to contact if not member. CRM-3711
226 $historyParams = array(
227 'group_id' => $groupId,
228 'contact_id' => $contactId,
232 'tracking' => $tracking,
234 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
235 $groupContact->status
= $status;
236 $groupContact->save();
240 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
242 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
244 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
248 * Get list of all the groups and groups for a contact.
250 * @param int $contactId
253 * @param bool $visibility
257 * this array has key-> group id and value group title
259 public static function getGroupList($contactId = 0, $visibility = FALSE) {
260 $group = new CRM_Contact_DAO_Group();
262 $select = $from = $where = '';
264 $select = 'SELECT civicrm_group.id, civicrm_group.title ';
265 $from = ' FROM civicrm_group ';
266 $where = " WHERE civicrm_group.is_active = 1 ";
268 $from .= ' , civicrm_group_contact ';
269 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
270 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
274 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
276 $groupBy = " GROUP BY civicrm_group.id";
278 $orderby = " ORDER BY civicrm_group.name";
279 $sql = $select . $from . $where . $groupBy . $orderby;
284 while ($group->fetch()) {
285 $values[$group->id
] = $group->title
;
292 * Get the list of groups for contact based on status of group membership.
294 * @param int $contactId
296 * @param string $status
297 * State of membership.
298 * @param int $numGroupContact
299 * Number of groups for a contact that should be shown.
301 * True if we are interested only in the count.
302 * @param bool $ignorePermission
303 * True if we should ignore permissions for the current user.
304 * useful in profile where permissions are limited for the user. If left
305 * at false only groups viewable by the current user are returned
306 * @param bool $onlyPublicGroups
307 * True if we want to hide system groups.
309 * @param bool $excludeHidden
311 * @param int $groupId
313 * @param bool $includeSmartGroups
314 * Include or Exclude Smart Group(s)
316 * @return array|int $values
317 * the relevant data object values for the contact or the total count when $count is TRUE
319 public static function getContactGroup(
322 $numGroupContact = NULL,
324 $ignorePermission = FALSE,
325 $onlyPublicGroups = FALSE,
326 $excludeHidden = TRUE,
328 $includeSmartGroups = FALSE
331 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
335 civicrm_group_contact.id as civicrm_group_contact_id,
336 civicrm_group.title as group_title,
337 civicrm_group.visibility as visibility,
338 civicrm_group_contact.status as status,
339 civicrm_group.id as group_id,
340 civicrm_group.is_hidden as is_hidden,
341 civicrm_subscription_history.date as date,
342 civicrm_subscription_history.method as method';
345 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
346 if (!$includeSmartGroups) {
347 $where .= " AND saved_search_id IS NULL";
349 if ($excludeHidden) {
350 $where .= " AND civicrm_group.is_hidden = 0 ";
352 $params = array(1 => array($contactId, 'Integer'));
353 if (!empty($status)) {
354 $where .= ' AND civicrm_group_contact.status = %2';
355 $params[2] = array($status, 'String');
357 if (!empty($groupId)) {
358 $where .= " AND civicrm_group.id = %3 ";
359 $params[3] = array($groupId, 'Integer');
362 'civicrm_group_contact' => 1,
363 'civicrm_group' => 1,
364 'civicrm_subscription_history' => 1,
366 $whereTables = array();
367 if ($ignorePermission) {
368 $permission = ' ( 1 ) ';
371 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
374 $from = CRM_Contact_BAO_Query
::fromClause($tables);
376 $where .= " AND $permission ";
378 if ($onlyPublicGroups) {
379 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
382 $order = $limit = '';
384 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
386 if ($numGroupContact) {
387 $limit = " LIMIT 0, $numGroupContact";
391 $sql = $select . $from . $where . $order . $limit;
394 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
398 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
400 while ($dao->fetch()) {
401 $id = $dao->civicrm_group_contact_id
;
402 $values[$id]['id'] = $id;
403 $values[$id]['group_id'] = $dao->group_id
;
404 $values[$id]['title'] = $dao->group_title
;
405 $values[$id]['visibility'] = $dao->visibility
;
406 $values[$id]['is_hidden'] = $dao->is_hidden
;
407 switch ($dao->status
) {
417 $prefix = 'pending_';
419 $values[$id][$prefix . 'date'] = $dao->date
;
420 $values[$id][$prefix . 'method'] = $dao->method
;
421 if ($status == 'Removed') {
422 $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 )";
423 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
424 if ($dateDAO->fetch()) {
425 $values[$id]['date_added'] = $dateDAO->date_added
;
434 * Returns membership details of a contact for a group.
436 * @param int $contactId
438 * @param int $groupID
439 * Id of a particular group.
440 * @param string $method
441 * If we want the subscription history details for a specific method.
446 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
447 $leftJoin = $where = $orderBy = NULL;
450 //CRM-13341 add group_id clause
452 LEFT JOIN civicrm_subscription_history
453 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
454 AND civicrm_subscription_history.group_id = {$groupID} )";
455 $where = "AND civicrm_subscription_history.method ='Email'";
456 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
460 FROM civicrm_group_contact
462 WHERE civicrm_group_contact.contact_id = %1
463 AND civicrm_group_contact.group_id = %2
469 1 => array($contactId, 'Integer'),
470 2 => array($groupID, 'Integer'),
472 $dao = CRM_Core_DAO
::executeQuery($query, $params);
478 * Method to get Group Id.
480 * @param int $groupContactID
481 * Id of a particular group.
486 public static function getGroupId($groupContactID) {
487 $dao = new CRM_Contact_DAO_GroupContact();
488 $dao->id
= $groupContactID;
490 return $dao->group_id
;
494 * Takes an associative array and creates / removes
495 * contacts from the groups
498 * @param array $params
499 * (reference ) an assoc array of name/value pairs.
500 * @param array $contactId
503 * @param bool $visibility
504 * @param string $method
506 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
507 $contactIds = array();
508 $contactIds[] = $contactId;
510 //if $visibility is true we are coming in via profile mean $method = 'Web'
511 $ignorePermission = FALSE;
513 $ignorePermission = TRUE;
517 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
518 NULL, FALSE, $ignorePermission
520 if (is_array($contactGroupList)) {
521 foreach ($contactGroupList as $key) {
522 $groupId = $key['group_id'];
523 $contactGroup[$groupId] = $groupId;
528 // get the list of all the groups
529 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
531 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
532 if (!is_array($params)) {
536 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
537 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
538 $contactGroup = array();
541 // check which values has to be add/remove contact from group
542 foreach ($allGroup as $key => $varValue) {
543 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
544 // add contact to group
545 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
547 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
548 // remove contact from group
549 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
555 * @param int $contactID
556 * @param int $groupID
560 public static function isContactInGroup($contactID, $groupID) {
561 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
562 !CRM_Utils_Rule
::positiveInteger($groupID)
568 array('group', 'IN', array($groupID), 0, 0),
569 array('contact_id', '=', $contactID, 0, 0),
571 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
573 if (!empty($contacts)) {
580 * Function merges the groups from otherContactID to mainContactID.
581 * along with subscription history
583 * @param int $mainContactId
584 * Contact id of main contact record.
585 * @param int $otherContactId
586 * Contact id of record which is going to merge.
588 * @see CRM_Dedupe_Merger::cpTables()
590 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
592 public static function mergeGroupContact($mainContactId, $otherContactId) {
594 1 => array($mainContactId, 'Integer'),
595 2 => array($otherContactId, 'Integer'),
598 // find all groups that are in otherContactID but not in mainContactID, copy them over
600 SELECT cOther.group_id
601 FROM civicrm_group_contact cOther
602 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
603 WHERE cOther.contact_id = %2
604 AND cMain.contact_id IS NULL
606 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
608 $otherGroupIDs = array();
609 while ($dao->fetch()) {
610 $otherGroupIDs[] = $dao->group_id
;
613 if (!empty($otherGroupIDs)) {
614 $otherGroupIDString = implode(',', $otherGroupIDs);
617 UPDATE civicrm_group_contact
619 WHERE contact_id = %2
620 AND group_id IN ( $otherGroupIDString )
622 CRM_Core_DAO
::executeQuery($sql, $params);
625 UPDATE civicrm_subscription_history
627 WHERE contact_id = %2
628 AND group_id IN ( $otherGroupIDString )
630 CRM_Core_DAO
::executeQuery($sql, $params);
634 SELECT cOther.group_id as group_id,
635 cOther.status as group_status
636 FROM civicrm_group_contact cMain
637 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
638 WHERE cMain.contact_id = %1
639 AND cOther.contact_id = %2
641 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
644 while ($dao->fetch()) {
645 // only copy it over if it has added status and migrate the history
646 if ($dao->group_status
== 'Added') {
647 $groupIDs[] = $dao->group_id
;
651 if (!empty($groupIDs)) {
652 $groupIDString = implode(',', $groupIDs);
655 UPDATE civicrm_group_contact
657 WHERE contact_id = %1
658 AND group_id IN ( $groupIDString )
660 CRM_Core_DAO
::executeQuery($sql, $params);
663 UPDATE civicrm_subscription_history
665 WHERE contact_id = %2
666 AND group_id IN ( $groupIDString )
668 CRM_Core_DAO
::executeQuery($sql, $params);
671 // delete all the other group contacts
674 FROM civicrm_group_contact
675 WHERE contact_id = %2
677 CRM_Core_DAO
::executeQuery($sql, $params);
681 FROM civicrm_subscription_history
682 WHERE contact_id = %2
684 CRM_Core_DAO
::executeQuery($sql, $params);
688 * Given an array of contact ids, add all the contacts to the group
690 * @param array $contactIDs
691 * The array of contact ids to be added.
692 * @param int $groupID
693 * The id of the group.
694 * @param string $method
695 * @param string $status
696 * @param NULL $tracking
699 * (total, added, notAdded) count of contacts added to group
701 public static function bulkAddContactsToGroup(
709 $numContactsAdded = 0;
710 $numContactsNotAdded = 0;
713 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
716 $subscriptioHistorySQL = "
717 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
721 $date = date('YmdHis');
723 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
724 while (!empty($contactIDs)) {
725 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
726 $contactStr = implode(',', $input);
728 // lets check their current status
730 SELECT GROUP_CONCAT(contact_id) as contactStr
731 FROM civicrm_group_contact
734 AND contact_id IN ( $contactStr )
737 1 => array($groupID, 'Integer'),
738 2 => array($status, 'String'),
741 $presentIDs = array();
742 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
744 $presentIDs = explode(',', $dao->contactStr
);
745 $presentIDs = array_flip($presentIDs);
748 $gcValues = $shValues = array();
749 foreach ($input as $cid) {
750 if (isset($presentIDs[$cid])) {
751 $numContactsNotAdded++
;
755 $gcValues[] = "( $groupID, $cid, '$status' )";
756 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
760 if (!empty($gcValues)) {
761 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
762 CRM_Core_DAO
::executeQuery($cgSQL);
764 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
765 CRM_Core_DAO
::executeQuery($shSQL);
769 return array($numContactsAdded, $numContactsNotAdded);
773 * Get options for a given field.
774 * @see CRM_Core_DAO::buildOptions
776 * @param string $fieldName
777 * @param string $context
778 * @see CRM_Core_DAO::buildOptionsContext
779 * @param array $props
780 * whatever is known about this dao object.
784 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
787 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
789 // Sort group list by hierarchy
790 // TODO: This will only work when api.entity is "group_contact". What about others?
791 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
792 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);