3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
35 class CRM_Contact_BAO_GroupContact
extends CRM_Contact_DAO_GroupContact
{
40 public function __construct() {
41 parent
::__construct();
45 * Takes an associative array and creates a groupContact object.
47 * the function extract all the params it needs to initialize the create a
48 * group object. the params array could contain additional unused name/value
51 * @param array $params
52 * (reference ) an assoc array of name/value pairs.
54 * @return CRM_Contact_BAO_Group
56 public static function add(&$params) {
58 $dataExists = self
::dataExists($params);
63 $groupContact = new CRM_Contact_BAO_GroupContact();
64 $groupContact->copyValues($params);
65 CRM_Contact_BAO_SubscriptionHistory
::create($params);
66 $groupContact->save();
71 * Check if there is data to create the object.
73 * @param array $params
74 * (reference ) an assoc array of name/value pairs.
78 public static function dataExists(&$params) {
79 // return if no data present
80 if ($params['group_id'] == 0) {
88 * Given the list of params in the params array, fetch the object
89 * and store the values in the values array
91 * @param array $params
92 * Input parameters to find object.
93 * @param array $values
94 * Output values of the object.
97 * (reference) the values that could be potentially assigned to smarty
99 public static function getValues(&$params, &$values) {
100 if (empty($params)) {
103 $values['group']['data'] = &CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
108 // get the total count of groups
109 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
119 * Given an array of contact ids, add all the contacts to the group
121 * @param array $contactIds
122 * The array of contact ids to be added.
123 * @param int $groupId
124 * The id of the group.
125 * @param string $method
126 * @param string $status
127 * @param int $tracking
130 * (total, added, notAdded) count of contacts added to group
132 public static function addContactsToGroup(
140 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
142 list($numContactsAdded, $numContactsNotAdded)
143 = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
145 // also reset the acl cache
146 $config = CRM_Core_Config
::singleton();
147 if (!$config->doNotResetCache
) {
148 CRM_ACL_BAO_Cache
::resetCache();
151 // reset the group contact cache for all group(s)
152 // if this group is being used as a smart group
153 CRM_Contact_BAO_GroupContactCache
::remove();
155 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
157 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
161 * Given an array of contact ids, remove all the contacts from the group
163 * @param array $contactIds
164 * (reference ) the array of contact ids to be removed.
165 * @param int $groupId
166 * The id of the group.
168 * @param string $method
169 * @param string $status
170 * @param NULL $tracking
173 * (total, removed, notRemoved) count of contacts removed to group
175 public static function removeContactsFromGroup(
182 if (!is_array($contactIds)) {
183 return array(0, 0, 0);
186 if ($status == 'Removed' ||
$status == 'Deleted') {
193 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
195 $date = date('YmdHis');
196 $numContactsRemoved = 0;
197 $numContactsNotRemoved = 0;
199 $group = new CRM_Contact_DAO_Group();
200 $group->id
= $groupId;
203 foreach ($contactIds as $contactId) {
204 if ($status == 'Deleted') {
205 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
206 $dao = CRM_Core_DAO
::executeQuery($query);
207 $historyParams = array(
208 'group_id' => $groupId,
209 'contact_id' => $contactId,
213 'tracking' => $tracking,
215 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
218 $groupContact = new CRM_Contact_DAO_GroupContact();
219 $groupContact->group_id
= $groupId;
220 $groupContact->contact_id
= $contactId;
221 // check if the selected contact id already a member, or if this is
222 // an opt-out of a smart group.
223 // if not a member remove to groupContact else keep the count of contacts that are not removed
224 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
225 // remove the contact from the group
226 $numContactsRemoved++
;
229 $numContactsNotRemoved++
;
232 //now we grant the negative membership to contact if not member. CRM-3711
233 $historyParams = array(
234 'group_id' => $groupId,
235 'contact_id' => $contactId,
239 'tracking' => $tracking,
241 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
242 $groupContact->status
= $status;
243 $groupContact->save();
247 // also reset the acl cache
248 $config = CRM_Core_Config
::singleton();
249 if (!$config->doNotResetCache
) {
250 CRM_ACL_BAO_Cache
::resetCache();
253 // reset the group contact cache for all group(s)
254 // if this group is being used as a smart group
255 CRM_Contact_BAO_GroupContactCache
::remove();
257 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
259 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
263 * Get list of all the groups and groups for a contact.
265 * @param int $contactId
268 * @param bool $visibility
272 * this array has key-> group id and value group title
274 public static function getGroupList($contactId = 0, $visibility = FALSE) {
275 $group = new CRM_Contact_DAO_Group();
277 $select = $from = $where = '';
279 $select = 'SELECT DISTINCT civicrm_group.id, civicrm_group.title ';
280 $from = ' FROM civicrm_group ';
281 $where = " WHERE civicrm_group.is_active = 1 ";
283 $from .= ' , civicrm_group_contact ';
284 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
285 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
289 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
292 $orderby = " ORDER BY civicrm_group.name";
293 $sql = $select . $from . $where . $orderby;
298 while ($group->fetch()) {
299 $values[$group->id
] = $group->title
;
306 * Get the list of groups for contact based on status of group membership.
308 * @param int $contactId
310 * @param string $status
311 * State of membership.
312 * @param int $numGroupContact
313 * Number of groups for a contact that should be shown.
315 * True if we are interested only in the count.
316 * @param bool $ignorePermission
317 * True if we should ignore permissions for the current user.
318 * useful in profile where permissions are limited for the user. If left
319 * at false only groups viewable by the current user are returned
320 * @param bool $onlyPublicGroups
321 * True if we want to hide system groups.
323 * @param bool $excludeHidden
325 * @return array (reference)|int $values
326 * the relevant data object values for the contact or
327 * the total count when $count is TRUE
329 public static function &getContactGroup(
332 $numGroupContact = NULL,
334 $ignorePermission = FALSE,
335 $onlyPublicGroups = FALSE,
336 $excludeHidden = TRUE,
340 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
344 civicrm_group_contact.id as civicrm_group_contact_id,
345 civicrm_group.title as group_title,
346 civicrm_group.visibility as visibility,
347 civicrm_group_contact.status as status,
348 civicrm_group.id as group_id,
349 civicrm_group.is_hidden as is_hidden,
350 civicrm_subscription_history.date as date,
351 civicrm_subscription_history.method as method';
354 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1 ";
356 if ($excludeHidden) {
357 $where .= " AND civicrm_group.is_hidden = 0 ";
360 $params = array(1 => array($contactId, 'Integer'));
361 if (!empty($status)) {
362 $where .= ' AND civicrm_group_contact.status = %2';
363 $params[2] = array($status, 'String');
365 if (!empty($groupId)) {
366 $where .= " AND civicrm_group.id = %3 ";
367 $params[3] = array($groupId, 'Integer');
370 'civicrm_group_contact' => 1,
371 'civicrm_group' => 1,
372 'civicrm_subscription_history' => 1,
374 $whereTables = array();
375 if ($ignorePermission) {
376 $permission = ' ( 1 ) ';
379 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
382 $from = CRM_Contact_BAO_Query
::fromClause($tables);
384 $where .= " AND $permission ";
386 if ($onlyPublicGroups) {
387 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
390 $order = $limit = '';
392 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
394 if ($numGroupContact) {
395 $limit = " LIMIT 0, $numGroupContact";
399 $sql = $select . $from . $where . $order . $limit;
402 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
406 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
408 while ($dao->fetch()) {
409 $id = $dao->civicrm_group_contact_id
;
410 $values[$id]['id'] = $id;
411 $values[$id]['group_id'] = $dao->group_id
;
412 $values[$id]['title'] = $dao->group_title
;
413 $values[$id]['visibility'] = $dao->visibility
;
414 $values[$id]['is_hidden'] = $dao->is_hidden
;
415 switch ($dao->status
) {
425 $prefix = 'pending_';
427 $values[$id][$prefix . 'date'] = $dao->date
;
428 $values[$id][$prefix . 'method'] = $dao->method
;
429 if ($status == 'Removed') {
430 $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 )";
431 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
432 if ($dateDAO->fetch()) {
433 $values[$id]['date_added'] = $dateDAO->date_added
;
442 * Returns membership details of a contact for a group.
444 * @param int $contactId
446 * @param int $groupID
447 * Id of a perticuler group.
448 * @param string $method
449 * If we want the subscription history details for a specific method.
454 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
455 $leftJoin = $where = $orderBy = NULL;
458 //CRM-13341 add group_id clause
460 LEFT JOIN civicrm_subscription_history
461 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
462 AND civicrm_subscription_history.group_id = {$groupID} )";
463 $where = "AND civicrm_subscription_history.method ='Email'";
464 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
468 FROM civicrm_group_contact
470 WHERE civicrm_group_contact.contact_id = %1
471 AND civicrm_group_contact.group_id = %2
477 1 => array($contactId, 'Integer'),
478 2 => array($groupID, 'Integer'),
480 $dao = CRM_Core_DAO
::executeQuery($query, $params);
486 * Method to get Group Id.
488 * @param int $groupContactID
489 * Id of a perticuler group.
494 public static function getGroupId($groupContactID) {
495 $dao = new CRM_Contact_DAO_GroupContact();
496 $dao->id
= $groupContactID;
498 return $dao->group_id
;
502 * Takes an associative array and creates / removes
503 * contacts from the groups
506 * @param array $params
507 * (reference ) an assoc array of name/value pairs.
508 * @param array $contactId
511 * @param bool $visibility
512 * @param string $method
516 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
517 $contactIds = array();
518 $contactIds[] = $contactId;
520 //if $visibility is true we are coming in via profile mean $method = 'Web'
521 $ignorePermission = FALSE;
523 $ignorePermission = TRUE;
527 $contactGroupList = &CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
528 NULL, FALSE, $ignorePermission
530 if (is_array($contactGroupList)) {
531 foreach ($contactGroupList as $key) {
532 $groupId = $key['group_id'];
533 $contactGroup[$groupId] = $groupId;
538 // get the list of all the groups
539 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
541 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
542 if (!is_array($params)) {
546 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
547 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
548 $contactGroup = array();
551 // check which values has to be add/remove contact from group
552 foreach ($allGroup as $key => $varValue) {
553 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
554 // add contact to group
555 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
557 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
558 // remove contact from group
559 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
565 * @param int $contactID
566 * @param int $groupID
570 public static function isContactInGroup($contactID, $groupID) {
571 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
572 !CRM_Utils_Rule
::positiveInteger($groupID)
578 array('group', 'IN', array($groupID => 1), 0, 0),
579 array('contact_id', '=', $contactID, 0, 0),
581 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
583 if (!empty($contacts)) {
590 * Function merges the groups from otherContactID to mainContactID.
591 * along with subscription history
593 * @param int $mainContactId
594 * Contact id of main contact record.
595 * @param int $otherContactId
596 * Contact id of record which is going to merge.
598 * @see CRM_Dedupe_Merger::cpTables()
600 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
605 public static function mergeGroupContact($mainContactId, $otherContactId) {
607 1 => array($mainContactId, 'Integer'),
608 2 => array($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);
621 $otherGroupIDs = array();
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 NULL $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 => array($groupID, 'Integer'),
751 2 => array($status, 'String'),
754 $presentIDs = array();
755 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
757 $presentIDs = explode(',', $dao->contactStr
);
758 $presentIDs = array_flip($presentIDs);
761 $gcValues = $shValues = array();
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 array($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 = array()) {
800 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
802 // Sort group list by hierarchy
803 // TODO: This will only work when api.entity is "group_contact". What about others?
804 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
805 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);