3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 class CRM_Contact_BAO_GroupContact
extends CRM_Contact_DAO_GroupContact
{
40 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 (reference ) an assoc array of name/value pairs
53 * @return object CRM_Contact_BAO_Group object
57 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 (reference ) an assoc array of name/value pairs
80 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 input parameters to find object
94 * @param array $values output values of the object
95 * @param array $ids the array that holds all the db ids
97 * @return array (reference) the values that could be potentially assigned to smarty
101 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 the array of contact ids to be added
124 * @param int $groupId the id of the group
125 * @param string $method
126 * @param string $status
127 * @param int $tracking
129 * @return array (total, added, notAdded) count of contacts added to group
133 static function addContactsToGroup(
142 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
144 list($numContactsAdded,
146 ) = self
::bulkAddContactsToGroup($contactIds,
153 // also reset the acl cache
154 $config = CRM_Core_Config
::singleton();
155 if (!$config->doNotResetCache
) {
156 CRM_ACL_BAO_Cache
::resetCache();
159 // reset the group contact cache for all group(s)
160 // if this group is being used as a smart group
161 CRM_Contact_BAO_GroupContactCache
::remove();
163 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
165 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
169 * Given an array of contact ids, remove all the contacts from the group
171 * @param array $contactIds (reference ) the array of contact ids to be removed
172 * @param int $groupId the id of the group
174 * @return array (total, removed, notRemoved) count of contacts removed to group
178 static function removeContactsFromGroup(
185 if (!is_array($contactIds)) {
186 return array(0, 0, 0);
189 if ($status == 'Removed' ||
$status == 'Deleted') {
196 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
198 $date = date('YmdHis');
199 $numContactsRemoved = 0;
200 $numContactsNotRemoved = 0;
202 $group = new CRM_Contact_DAO_Group();
203 $group->id
= $groupId;
206 foreach ($contactIds as $contactId) {
207 if ($status == 'Deleted') {
208 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
209 $dao = CRM_Core_DAO
::executeQuery($query);
210 $historyParams = array(
211 'group_id' => $groupId,
212 'contact_id' => $contactId,
216 'tracking' => $tracking,
218 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
221 $groupContact = new CRM_Contact_DAO_GroupContact();
222 $groupContact->group_id
= $groupId;
223 $groupContact->contact_id
= $contactId;
224 // check if the selected contact id already a member, or if this is
225 // an opt-out of a smart group.
226 // if not a member remove to groupContact else keep the count of contacts that are not removed
227 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
228 // remove the contact from the group
229 $numContactsRemoved++
;
232 $numContactsNotRemoved++
;
235 //now we grant the negative membership to contact if not member. CRM-3711
236 $historyParams = array(
237 'group_id' => $groupId,
238 'contact_id' => $contactId,
242 'tracking' => $tracking,
244 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
245 $groupContact->status
= $status;
246 $groupContact->save();
250 // also reset the acl cache
251 $config = CRM_Core_Config
::singleton();
252 if (!$config->doNotResetCache
) {
253 CRM_ACL_BAO_Cache
::resetCache();
256 // reset the group contact cache for all group(s)
257 // if this group is being used as a smart group
258 CRM_Contact_BAO_GroupContactCache
::remove();
260 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
262 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
266 * Function to get list of all the groups and groups for a contact
268 * @param int $contactId contact id
272 * @return array $values this array has key-> group id and value group title
275 static function getGroupList($contactId = 0, $visibility = FALSE) {
276 $group = new CRM_Contact_DAO_Group();
278 $select = $from = $where = '';
280 $select = 'SELECT DISTINCT civicrm_group.id, civicrm_group.title ';
281 $from = ' FROM civicrm_group ';
282 $where = " WHERE civicrm_group.is_active = 1 ";
284 $from .= ' , civicrm_group_contact ';
285 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
286 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
290 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
293 $orderby = " ORDER BY civicrm_group.name";
294 $sql = $select . $from . $where . $orderby;
299 while ($group->fetch()) {
300 $values[$group->id
] = $group->title
;
307 * Function to get the list of groups for contact based on status of group membership
309 * @param int $contactId contact id
310 * @param string $status state of membership
311 * @param int $numGroupContact number of groups for a contact that should be shown
312 * @param boolean $count true if we are interested only in the count
313 * @param boolean $ignorePermission true if we should ignore permissions for the current user
314 * useful in profile where permissions are limited for the user. If left
315 * at false only groups viewable by the current user are returned
316 * @param boolean $onlyPublicGroups true if we want to hide system groups
318 * @return array (reference )|int $values the relevant data object values for the contact or
319 * the total count when $count is true
323 static function &getContactGroup(
326 $numGroupContact = NULL,
328 $ignorePermission = FALSE,
329 $onlyPublicGroups = FALSE,
330 $excludeHidden = TRUE
333 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
337 civicrm_group_contact.id as civicrm_group_contact_id,
338 civicrm_group.title as group_title,
339 civicrm_group.visibility as visibility,
340 civicrm_group_contact.status as status,
341 civicrm_group.id as group_id,
342 civicrm_group.is_hidden as is_hidden,
343 civicrm_subscription_history.date as date,
344 civicrm_subscription_history.method as method';
347 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1 ";
349 if ($excludeHidden) {
350 $where .= " AND civicrm_group.is_hidden = 0 ";
353 $params = array(1 => array($contactId, 'Integer'));
354 if (!empty($status)) {
355 $where .= ' AND civicrm_group_contact.status = %2';
356 $params[2] = array($status, 'String');
359 'civicrm_group_contact' => 1,
360 'civicrm_group' => 1,
361 'civicrm_subscription_history' => 1,
363 $whereTables = array();
364 if ($ignorePermission) {
365 $permission = ' ( 1 ) ';
368 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
371 $from = CRM_Contact_BAO_Query
::fromClause($tables);
373 $where .= " AND $permission ";
375 if ($onlyPublicGroups) {
376 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
379 $order = $limit = '';
381 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
383 if ($numGroupContact) {
384 $limit = " LIMIT 0, $numGroupContact";
388 $sql = $select . $from . $where . $order . $limit;
391 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
395 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
397 while ($dao->fetch()) {
398 $id = $dao->civicrm_group_contact_id
;
399 $values[$id]['id'] = $id;
400 $values[$id]['group_id'] = $dao->group_id
;
401 $values[$id]['title'] = $dao->group_title
;
402 $values[$id]['visibility'] = $dao->visibility
;
403 $values[$id]['is_hidden'] = $dao->is_hidden
;
404 switch ($dao->status
) {
414 $prefix = 'pending_';
416 $values[$id][$prefix . 'date'] = $dao->date
;
417 $values[$id][$prefix . 'method'] = $dao->method
;
418 if ($status == 'Removed') {
419 $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 )";
420 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
421 if ($dateDAO->fetch()) {
422 $values[$id]['date_added'] = $dateDAO->date_added
;
431 * Returns membership details of a contact for a group
433 * @param int $contactId id of the contact
434 * @param int $groupID Id of a perticuler group
435 * @param string $method If we want the subscription history details for a specific method
437 * @return object of group contact
441 static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
442 $leftJoin = $where = $orderBy = null;
445 //CRM-13341 add group_id clause
447 LEFT JOIN civicrm_subscription_history
448 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
449 AND civicrm_subscription_history.group_id = {$groupID} )";
450 $where = "AND civicrm_subscription_history.method ='Email'";
451 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
455 FROM civicrm_group_contact
457 WHERE civicrm_group_contact.contact_id = %1
458 AND civicrm_group_contact.group_id = %2
464 1 => array($contactId, 'Integer'),
465 2 => array($groupID, 'Integer'),
467 $dao = CRM_Core_DAO
::executeQuery($query, $params);
473 * Method to get Group Id
475 * @param int $groupContactID Id of a perticuler group
482 static function getGroupId($groupContactID) {
483 $dao = new CRM_Contact_DAO_GroupContact();
484 $dao->id
= $groupContactID;
486 return $dao->group_id
;
490 * takes an associative array and creates / removes
491 * contacts from the groups
494 * @param array $params (reference ) an assoc array of name/value pairs
495 * @param array $contactId contact id
501 static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
502 $contactIds = array();
503 $contactIds[] = $contactId;
505 //if $visibility is true we are coming in via profile mean $method = 'Web'
506 $ignorePermission = FALSE;
508 $ignorePermission = TRUE;
512 $contactGroupList = &CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
513 NULL, FALSE, $ignorePermission
515 if (is_array($contactGroupList)) {
516 foreach ($contactGroupList as $key) {
517 $groupId = $key['group_id'];
518 $contactGroup[$groupId] = $groupId;
523 // get the list of all the groups
524 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
526 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
527 if (!is_array($params)) {
531 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
532 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
533 $contactGroup = array();
536 // check which values has to be add/remove contact from group
537 foreach ($allGroup as $key => $varValue) {
538 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
539 // add contact to group
540 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
542 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
543 // remove contact from group
544 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
549 static function isContactInGroup($contactID, $groupID) {
550 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
551 !CRM_Utils_Rule
::positiveInteger($groupID)
557 array('group', 'IN', array($groupID => 1), 0, 0),
558 array('contact_id', '=', $contactID, 0, 0),
560 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
562 if (!empty($contacts)) {
569 * Function merges the groups from otherContactID to mainContactID
570 * along with subscription history
572 * @param int $mainContactId contact id of main contact record.
573 * @param int $otherContactId contact id of record which is going to merge.
575 * @see CRM_Dedupe_Merger::cpTables()
577 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
582 static function mergeGroupContact($mainContactId, $otherContactId) {
583 $params = array(1 => array($mainContactId, 'Integer'),
584 2 => array($otherContactId, 'Integer'),
587 // find all groups that are in otherContactID but not in mainContactID, copy them over
589 SELECT cOther.group_id
590 FROM civicrm_group_contact cOther
591 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
592 WHERE cOther.contact_id = %2
593 AND cMain.contact_id IS NULL
595 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
597 $otherGroupIDs = array();
598 while ($dao->fetch()) {
599 $otherGroupIDs[] = $dao->group_id
;
602 if (!empty($otherGroupIDs)) {
603 $otherGroupIDString = implode(',', $otherGroupIDs);
606 UPDATE civicrm_group_contact
608 WHERE contact_id = %2
609 AND group_id IN ( $otherGroupIDString )
611 CRM_Core_DAO
::executeQuery($sql, $params);
614 UPDATE civicrm_subscription_history
616 WHERE contact_id = %2
617 AND group_id IN ( $otherGroupIDString )
619 CRM_Core_DAO
::executeQuery($sql, $params);
623 SELECT cOther.group_id as group_id,
624 cOther.status as group_status
625 FROM civicrm_group_contact cMain
626 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
627 WHERE cMain.contact_id = %1
628 AND cOther.contact_id = %2
630 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
633 while ($dao->fetch()) {
634 // only copy it over if it has added status and migrate the history
635 if ($dao->group_status
== 'Added') {
636 $groupIDs[] = $dao->group_id
;
640 if (!empty($groupIDs)) {
641 $groupIDString = implode(',', $groupIDs);
644 UPDATE civicrm_group_contact
646 WHERE contact_id = %1
647 AND group_id IN ( $groupIDString )
649 CRM_Core_DAO
::executeQuery($sql, $params);
652 UPDATE civicrm_subscription_history
654 WHERE contact_id = %2
655 AND group_id IN ( $groupIDString )
657 CRM_Core_DAO
::executeQuery($sql, $params);
660 // delete all the other group contacts
663 FROM civicrm_group_contact
664 WHERE contact_id = %2
666 CRM_Core_DAO
::executeQuery($sql, $params);
670 FROM civicrm_subscription_history
671 WHERE contact_id = %2
673 CRM_Core_DAO
::executeQuery($sql, $params);
677 * Given an array of contact ids, add all the contacts to the group
679 * @param array $contactIds (reference ) the array of contact ids to be added
680 * @param int $groupId the id of the group
682 * @return array (total, added, notAdded) count of contacts added to group
686 static function bulkAddContactsToGroup(
694 $numContactsAdded = 0;
695 $numContactsNotAdded = 0;
698 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
701 $subscriptioHistorySQL = "
702 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
706 $date = date('YmdHis');
708 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
709 while (!empty($contactIDs)) {
710 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
711 $contactStr = implode(',', $input);
713 // lets check their current status
715 SELECT GROUP_CONCAT(contact_id) as contactStr
716 FROM civicrm_group_contact
719 AND contact_id IN ( $contactStr )
721 $params = array(1 => array($groupID, 'Integer'),
722 2 => array($status, 'String'),
725 $presentIDs = array();
726 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
728 $presentIDs = explode(',', $dao->contactStr
);
729 $presentIDs = array_flip($presentIDs);
732 $gcValues = $shValues = array();
733 foreach ($input as $cid) {
734 if (isset($presentIDs[$cid])) {
735 $numContactsNotAdded++
;
739 $gcValues[] = "( $groupID, $cid, '$status' )";
740 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
744 if (!empty($gcValues)) {
745 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
746 CRM_Core_DAO
::executeQuery($cgSQL);
748 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
749 CRM_Core_DAO
::executeQuery($shSQL);
753 return array($numContactsAdded, $numContactsNotAdded);