3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 object
57 public static function add(&$params) {
59 $dataExists = self
::dataExists($params);
64 $groupContact = new CRM_Contact_BAO_GroupContact();
65 $groupContact->copyValues($params);
66 CRM_Contact_BAO_SubscriptionHistory
::create($params);
67 $groupContact->save();
72 * Check if there is data to create the object
74 * @param array $params
75 * (reference ) an assoc array of name/value pairs.
80 public static function dataExists(&$params) {
81 // return if no data present
82 if ($params['group_id'] == 0) {
90 * Given the list of params in the params array, fetch the object
91 * and store the values in the values array
93 * @param array $params
94 * Input parameters to find object.
95 * @param array $values
96 * Output values of the object.
98 * @return array (reference) the values that could be potentially assigned to smarty
101 public static function getValues(&$params, &$values) {
102 if (empty($params)) {
105 $values['group']['data'] = &CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
110 // get the total count of groups
111 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
121 * Given an array of contact ids, add all the contacts to the group
123 * @param array $contactIds
124 * The array of contact ids to be added.
125 * @param int $groupId
126 * The id of the group.
127 * @param string $method
128 * @param string $status
129 * @param int $tracking
131 * @return array (total, added, notAdded) count of contacts added to group
134 static function addContactsToGroup(
143 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
145 list($numContactsAdded,
147 ) = self
::bulkAddContactsToGroup($contactIds,
154 // also reset the acl cache
155 $config = CRM_Core_Config
::singleton();
156 if (!$config->doNotResetCache
) {
157 CRM_ACL_BAO_Cache
::resetCache();
160 // reset the group contact cache for all group(s)
161 // if this group is being used as a smart group
162 CRM_Contact_BAO_GroupContactCache
::remove();
164 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
166 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
170 * Given an array of contact ids, remove all the contacts from the group
172 * @param array $contactIds
173 * (reference ) the array of contact ids to be removed.
174 * @param int $groupId
175 * The id of the group.
177 * @param string $method
178 * @param string $status
179 * @param NULL $tracking
181 * @return array (total, removed, notRemoved) count of contacts removed to group
184 static function removeContactsFromGroup(
191 if (!is_array($contactIds)) {
192 return array(0, 0, 0);
195 if ($status == 'Removed' ||
$status == 'Deleted') {
202 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
204 $date = date('YmdHis');
205 $numContactsRemoved = 0;
206 $numContactsNotRemoved = 0;
208 $group = new CRM_Contact_DAO_Group();
209 $group->id
= $groupId;
212 foreach ($contactIds as $contactId) {
213 if ($status == 'Deleted') {
214 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
215 $dao = CRM_Core_DAO
::executeQuery($query);
216 $historyParams = array(
217 'group_id' => $groupId,
218 'contact_id' => $contactId,
222 'tracking' => $tracking,
224 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
227 $groupContact = new CRM_Contact_DAO_GroupContact();
228 $groupContact->group_id
= $groupId;
229 $groupContact->contact_id
= $contactId;
230 // check if the selected contact id already a member, or if this is
231 // an opt-out of a smart group.
232 // if not a member remove to groupContact else keep the count of contacts that are not removed
233 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
234 // remove the contact from the group
235 $numContactsRemoved++
;
238 $numContactsNotRemoved++
;
241 //now we grant the negative membership to contact if not member. CRM-3711
242 $historyParams = array(
243 'group_id' => $groupId,
244 'contact_id' => $contactId,
248 'tracking' => $tracking,
250 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
251 $groupContact->status
= $status;
252 $groupContact->save();
256 // also reset the acl cache
257 $config = CRM_Core_Config
::singleton();
258 if (!$config->doNotResetCache
) {
259 CRM_ACL_BAO_Cache
::resetCache();
262 // reset the group contact cache for all group(s)
263 // if this group is being used as a smart group
264 CRM_Contact_BAO_GroupContactCache
::remove();
266 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
268 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
272 * Get list of all the groups and groups for a contact
274 * @param int $contactId
277 * @param bool $visibility
280 * @return array $values this array has key-> group id and value group title
283 public static function getGroupList($contactId = 0, $visibility = FALSE) {
284 $group = new CRM_Contact_DAO_Group();
286 $select = $from = $where = '';
288 $select = 'SELECT DISTINCT civicrm_group.id, civicrm_group.title ';
289 $from = ' FROM civicrm_group ';
290 $where = " WHERE civicrm_group.is_active = 1 ";
292 $from .= ' , civicrm_group_contact ';
293 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
294 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
298 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
301 $orderby = " ORDER BY civicrm_group.name";
302 $sql = $select . $from . $where . $orderby;
307 while ($group->fetch()) {
308 $values[$group->id
] = $group->title
;
315 * Get the list of groups for contact based on status of group membership
317 * @param int $contactId
319 * @param string $status
320 * State of membership.
321 * @param int $numGroupContact
322 * Number of groups for a contact that should be shown.
324 * True if we are interested only in the count.
325 * @param bool $ignorePermission
326 * True if we should ignore permissions for the current user.
327 * useful in profile where permissions are limited for the user. If left
328 * at false only groups viewable by the current user are returned
329 * @param bool $onlyPublicGroups
330 * True if we want to hide system groups.
332 * @param bool $excludeHidden
334 * @return array (reference )|int $values the relevant data object values for the contact or
335 * the total count when $count is true
339 static function &getContactGroup(
342 $numGroupContact = NULL,
344 $ignorePermission = FALSE,
345 $onlyPublicGroups = FALSE,
346 $excludeHidden = TRUE,
350 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
354 civicrm_group_contact.id as civicrm_group_contact_id,
355 civicrm_group.title as group_title,
356 civicrm_group.visibility as visibility,
357 civicrm_group_contact.status as status,
358 civicrm_group.id as group_id,
359 civicrm_group.is_hidden as is_hidden,
360 civicrm_subscription_history.date as date,
361 civicrm_subscription_history.method as method';
364 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1 ";
366 if ($excludeHidden) {
367 $where .= " AND civicrm_group.is_hidden = 0 ";
370 $params = array(1 => array($contactId, 'Integer'));
371 if (!empty($status)) {
372 $where .= ' AND civicrm_group_contact.status = %2';
373 $params[2] = array($status, 'String');
375 if (!empty($groupId)) {
376 $where .= " AND civicrm_group.id = %3 ";
377 $params[3] = array($groupId, 'Integer');
380 'civicrm_group_contact' => 1,
381 'civicrm_group' => 1,
382 'civicrm_subscription_history' => 1,
384 $whereTables = array();
385 if ($ignorePermission) {
386 $permission = ' ( 1 ) ';
389 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
392 $from = CRM_Contact_BAO_Query
::fromClause($tables);
394 $where .= " AND $permission ";
396 if ($onlyPublicGroups) {
397 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
400 $order = $limit = '';
402 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
404 if ($numGroupContact) {
405 $limit = " LIMIT 0, $numGroupContact";
409 $sql = $select . $from . $where . $order . $limit;
412 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
416 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
418 while ($dao->fetch()) {
419 $id = $dao->civicrm_group_contact_id
;
420 $values[$id]['id'] = $id;
421 $values[$id]['group_id'] = $dao->group_id
;
422 $values[$id]['title'] = $dao->group_title
;
423 $values[$id]['visibility'] = $dao->visibility
;
424 $values[$id]['is_hidden'] = $dao->is_hidden
;
425 switch ($dao->status
) {
435 $prefix = 'pending_';
437 $values[$id][$prefix . 'date'] = $dao->date
;
438 $values[$id][$prefix . 'method'] = $dao->method
;
439 if ($status == 'Removed') {
440 $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 )";
441 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
442 if ($dateDAO->fetch()) {
443 $values[$id]['date_added'] = $dateDAO->date_added
;
452 * Returns membership details of a contact for a group
454 * @param int $contactId
456 * @param int $groupID
457 * Id of a perticuler group.
458 * @param string $method
459 * If we want the subscription history details for a specific method.
461 * @return object of group contact
464 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
465 $leftJoin = $where = $orderBy = NULL;
468 //CRM-13341 add group_id clause
470 LEFT JOIN civicrm_subscription_history
471 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
472 AND civicrm_subscription_history.group_id = {$groupID} )";
473 $where = "AND civicrm_subscription_history.method ='Email'";
474 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
478 FROM civicrm_group_contact
480 WHERE civicrm_group_contact.contact_id = %1
481 AND civicrm_group_contact.group_id = %2
487 1 => array($contactId, 'Integer'),
488 2 => array($groupID, 'Integer'),
490 $dao = CRM_Core_DAO
::executeQuery($query, $params);
496 * Method to get Group Id
498 * @param int $groupContactID
499 * Id of a perticuler group.
505 public static function getGroupId($groupContactID) {
506 $dao = new CRM_Contact_DAO_GroupContact();
507 $dao->id
= $groupContactID;
509 return $dao->group_id
;
513 * Takes an associative array and creates / removes
514 * contacts from the groups
517 * @param array $params
518 * (reference ) an assoc array of name/value pairs.
519 * @param array $contactId
522 * @param bool $visibility
523 * @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 => 1), 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
617 public static function mergeGroupContact($mainContactId, $otherContactId) {
618 $params = array(1 => array($mainContactId, 'Integer'),
619 2 => array($otherContactId, 'Integer'),
622 // find all groups that are in otherContactID but not in mainContactID, copy them over
624 SELECT cOther.group_id
625 FROM civicrm_group_contact cOther
626 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
627 WHERE cOther.contact_id = %2
628 AND cMain.contact_id IS NULL
630 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
632 $otherGroupIDs = array();
633 while ($dao->fetch()) {
634 $otherGroupIDs[] = $dao->group_id
;
637 if (!empty($otherGroupIDs)) {
638 $otherGroupIDString = implode(',', $otherGroupIDs);
641 UPDATE civicrm_group_contact
643 WHERE contact_id = %2
644 AND group_id IN ( $otherGroupIDString )
646 CRM_Core_DAO
::executeQuery($sql, $params);
649 UPDATE civicrm_subscription_history
651 WHERE contact_id = %2
652 AND group_id IN ( $otherGroupIDString )
654 CRM_Core_DAO
::executeQuery($sql, $params);
658 SELECT cOther.group_id as group_id,
659 cOther.status as group_status
660 FROM civicrm_group_contact cMain
661 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
662 WHERE cMain.contact_id = %1
663 AND cOther.contact_id = %2
665 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
668 while ($dao->fetch()) {
669 // only copy it over if it has added status and migrate the history
670 if ($dao->group_status
== 'Added') {
671 $groupIDs[] = $dao->group_id
;
675 if (!empty($groupIDs)) {
676 $groupIDString = implode(',', $groupIDs);
679 UPDATE civicrm_group_contact
681 WHERE contact_id = %1
682 AND group_id IN ( $groupIDString )
684 CRM_Core_DAO
::executeQuery($sql, $params);
687 UPDATE civicrm_subscription_history
689 WHERE contact_id = %2
690 AND group_id IN ( $groupIDString )
692 CRM_Core_DAO
::executeQuery($sql, $params);
695 // delete all the other group contacts
698 FROM civicrm_group_contact
699 WHERE contact_id = %2
701 CRM_Core_DAO
::executeQuery($sql, $params);
705 FROM civicrm_subscription_history
706 WHERE contact_id = %2
708 CRM_Core_DAO
::executeQuery($sql, $params);
712 * Given an array of contact ids, add all the contacts to the group
714 * @param array $contactIDs
715 * The array of contact ids to be added.
716 * @param int $groupID
717 * The id of the group.
718 * @param string $method
719 * @param string $status
720 * @param NULL $tracking
722 * @return array (total, added, notAdded) count of contacts added to group
725 static function bulkAddContactsToGroup(
733 $numContactsAdded = 0;
734 $numContactsNotAdded = 0;
737 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
740 $subscriptioHistorySQL = "
741 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
745 $date = date('YmdHis');
747 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
748 while (!empty($contactIDs)) {
749 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
750 $contactStr = implode(',', $input);
752 // lets check their current status
754 SELECT GROUP_CONCAT(contact_id) as contactStr
755 FROM civicrm_group_contact
758 AND contact_id IN ( $contactStr )
760 $params = array(1 => array($groupID, 'Integer'),
761 2 => array($status, 'String'),
764 $presentIDs = array();
765 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
767 $presentIDs = explode(',', $dao->contactStr
);
768 $presentIDs = array_flip($presentIDs);
771 $gcValues = $shValues = array();
772 foreach ($input as $cid) {
773 if (isset($presentIDs[$cid])) {
774 $numContactsNotAdded++
;
778 $gcValues[] = "( $groupID, $cid, '$status' )";
779 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
783 if (!empty($gcValues)) {
784 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
785 CRM_Core_DAO
::executeQuery($cgSQL);
787 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
788 CRM_Core_DAO
::executeQuery($shSQL);
792 return array($numContactsAdded, $numContactsNotAdded);
796 * Get options for a given field.
797 * @see CRM_Core_DAO::buildOptions
799 * @param string $fieldName
800 * @param string $context
801 * : @see CRM_Core_DAO::buildOptionsContext.
802 * @param array $props
803 * : whatever is known about this dao object.
807 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
810 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
812 // Sort group list by hierarchy
813 // TODO: This will only work when api.entity is "group_contact". What about others?
814 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
815 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);