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 (reference ) the array of contact ids to be added
124 * @param int $groupId the id of the group
126 * @return array (total, added, notAdded) count of contacts added to group
130 static function addContactsToGroup(
139 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
141 list($numContactsAdded,
143 ) = self
::bulkAddContactsToGroup($contactIds,
150 // also reset the acl cache
151 $config = CRM_Core_Config
::singleton();
152 if (!$config->doNotResetCache
) {
153 CRM_ACL_BAO_Cache
::resetCache();
156 // reset the group contact cache for all group(s)
157 // if this group is being used as a smart group
158 CRM_Contact_BAO_GroupContactCache
::remove();
160 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
162 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
166 * Given an array of contact ids, remove all the contacts from the group
168 * @param array $contactIds (reference ) the array of contact ids to be removed
169 * @param int $groupId the id of the group
171 * @return array (total, removed, notRemoved) count of contacts removed to group
175 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 * Function to get list of all the groups and groups for a contact
265 * @param int $contactId contact id
269 * @return array $values this array has key-> group id and value group title
272 static function getGroupList($contactId = 0, $visibility = FALSE) {
273 $group = new CRM_Contact_DAO_Group();
275 $select = $from = $where = '';
277 $select = 'SELECT DISTINCT civicrm_group.id, civicrm_group.title ';
278 $from = ' FROM civicrm_group ';
279 $where = " WHERE civicrm_group.is_active = 1 ";
281 $from .= ' , civicrm_group_contact ';
282 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
283 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
287 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
290 $orderby = " ORDER BY civicrm_group.name";
291 $sql = $select . $from . $where . $orderby;
296 while ($group->fetch()) {
297 $values[$group->id
] = $group->title
;
304 * Function to get the list of groups for contact based on status of group membership
306 * @param int $contactId contact id
307 * @param string $status state of membership
308 * @param int $numGroupContact number of groups for a contact that should be shown
309 * @param boolean $count true if we are interested only in the count
310 * @param boolean $ignorePermission true if we should ignore permissions for the current user
311 * useful in profile where permissions are limited for the user. If left
312 * at false only groups viewable by the current user are returned
313 * @param boolean $onlyPublicGroups true if we want to hide system groups
315 * @return array (reference )|int $values the relevant data object values for the contact or
316 * the total count when $count is true
320 static function &getContactGroup(
323 $numGroupContact = NULL,
325 $ignorePermission = FALSE,
326 $onlyPublicGroups = FALSE,
327 $excludeHidden = TRUE
330 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
334 civicrm_group_contact.id as civicrm_group_contact_id,
335 civicrm_group.title as group_title,
336 civicrm_group.visibility as visibility,
337 civicrm_group_contact.status as status,
338 civicrm_group.id as group_id,
339 civicrm_group.is_hidden as is_hidden,
340 civicrm_subscription_history.date as date,
341 civicrm_subscription_history.method as method';
344 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1 ";
346 if ($excludeHidden) {
347 $where .= " AND civicrm_group.is_hidden = 0 ";
350 $params = array(1 => array($contactId, 'Integer'));
351 if (!empty($status)) {
352 $where .= ' AND civicrm_group_contact.status = %2';
353 $params[2] = array($status, 'String');
356 'civicrm_group_contact' => 1,
357 'civicrm_group' => 1,
358 'civicrm_subscription_history' => 1,
360 $whereTables = array();
361 if ($ignorePermission) {
362 $permission = ' ( 1 ) ';
365 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
368 $from = CRM_Contact_BAO_Query
::fromClause($tables);
370 $where .= " AND $permission ";
372 if ($onlyPublicGroups) {
373 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
376 $order = $limit = '';
378 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
380 if ($numGroupContact) {
381 $limit = " LIMIT 0, $numGroupContact";
385 $sql = $select . $from . $where . $order . $limit;
388 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
392 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
394 while ($dao->fetch()) {
395 $id = $dao->civicrm_group_contact_id
;
396 $values[$id]['id'] = $id;
397 $values[$id]['group_id'] = $dao->group_id
;
398 $values[$id]['title'] = $dao->group_title
;
399 $values[$id]['visibility'] = $dao->visibility
;
400 $values[$id]['is_hidden'] = $dao->is_hidden
;
401 switch ($dao->status
) {
411 $prefix = 'pending_';
413 $values[$id][$prefix . 'date'] = $dao->date
;
414 $values[$id][$prefix . 'method'] = $dao->method
;
415 if ($status == 'Removed') {
416 $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 )";
417 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
418 if ($dateDAO->fetch()) {
419 $values[$id]['date_added'] = $dateDAO->date_added
;
428 * Returns membership details of a contact for a group
430 * @param int $contactId id of the contact
431 * @param int $groupID Id of a perticuler group
432 * @param string $method If we want the subscription history details for a specific method
434 * @return object of group contact
438 function &getMembershipDetail($contactId, $groupID, $method = 'Email') {
439 $leftJoin = $where = $orderBy = null;
442 //CRM-13341 add group_id clause
444 LEFT JOIN civicrm_subscription_history
445 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
446 AND civicrm_subscription_history.group_id = {$groupID} )";
447 $where = "AND civicrm_subscription_history.method ='Email'";
448 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
452 FROM civicrm_group_contact
454 WHERE civicrm_group_contact.contact_id = %1
455 AND civicrm_group_contact.group_id = %2
461 1 => array($contactId, 'Integer'),
462 2 => array($groupID, 'Integer'),
464 $dao = CRM_Core_DAO
::executeQuery($query, $params);
470 * Method to update the Status of Group member form 'Pending' to 'Added'
472 * @param int $contactId id of the contact
474 * @param int $groupID Id of a perticuler group
476 * @param mixed $tracking tracking information for history
478 * @return null If success
482 static function updateGroupMembershipStatus($contactId, $groupID, $method = 'Email', $tracking = NULL) {
483 if (!isset($contactId) && !isset($groupID)) {
484 return CRM_Core_Error
::fatal("$contactId or $groupID should not empty");
488 UPDATE civicrm_group_contact
489 SET civicrm_group_contact.status = 'Added'
490 WHERE civicrm_group_contact.contact_id = %1
491 AND civicrm_group_contact.group_id = %2";
493 1 => array($contactId, 'Integer'),
494 2 => array($groupID, 'Integer'),
497 $dao = CRM_Core_DAO
::executeQuery($query, $params);
500 'contact_id' => $contactId,
501 'group_id' => $groupID,
504 'tracking' => $tracking,
507 CRM_Contact_BAO_SubscriptionHistory
::create($params);
512 * Method to get Group Id
514 * @param int $groupContactID Id of a perticuler group
521 static function getGroupId($groupContactID) {
522 $dao = new CRM_Contact_DAO_GroupContact();
523 $dao->id
= $groupContactID;
525 return $dao->group_id
;
529 * takes an associative array and creates / removes
530 * contacts from the groups
533 * @param array $params (reference ) an assoc array of name/value pairs
534 * @param array $contactId contact id
540 static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
541 $contactIds = array();
542 $contactIds[] = $contactId;
544 //if $visibility is true we are coming in via profile mean $method = 'Web'
545 $ignorePermission = FALSE;
547 $ignorePermission = TRUE;
551 $contactGroupList = &CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
552 NULL, FALSE, $ignorePermission
554 if (is_array($contactGroupList)) {
555 foreach ($contactGroupList as $key) {
556 $groupId = $key['group_id'];
557 $contactGroup[$groupId] = $groupId;
562 // get the list of all the groups
563 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
565 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
566 if (!is_array($params)) {
570 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
571 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
572 $contactGroup = array();
575 // check which values has to be add/remove contact from group
576 foreach ($allGroup as $key => $varValue) {
577 if (CRM_Utils_Array
::value($key, $params) && !array_key_exists($key, $contactGroup)) {
578 // add contact to group
579 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
581 elseif (!CRM_Utils_Array
::value($key, $params) && array_key_exists($key, $contactGroup)) {
582 // remove contact from group
583 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
588 static function isContactInGroup($contactID, $groupID) {
589 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
590 !CRM_Utils_Rule
::positiveInteger($groupID)
596 array('group', 'IN', array($groupID => 1), 0, 0),
597 array('contact_id', '=', $contactID, 0, 0),
599 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
601 if (!empty($contacts)) {
608 * Function merges the groups from otherContactID to mainContactID
609 * along with subscription history
611 * @param int $mainContactId contact id of main contact record.
612 * @param int $otherContactId contact id of record which is going to merge.
614 * @see CRM_Dedupe_Merger::cpTables()
616 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
621 static function mergeGroupContact($mainContactId, $otherContactId) {
622 $params = array(1 => array($mainContactId, 'Integer'),
623 2 => array($otherContactId, 'Integer'),
626 // find all groups that are in otherContactID but not in mainContactID, copy them over
628 SELECT cOther.group_id
629 FROM civicrm_group_contact cOther
630 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
631 WHERE cOther.contact_id = %2
632 AND cMain.contact_id IS NULL
634 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
636 $otherGroupIDs = array();
637 while ($dao->fetch()) {
638 $otherGroupIDs[] = $dao->group_id
;
641 if (!empty($otherGroupIDs)) {
642 $otherGroupIDString = implode(',', $otherGroupIDs);
645 UPDATE civicrm_group_contact
647 WHERE contact_id = %2
648 AND group_id IN ( $otherGroupIDString )
650 CRM_Core_DAO
::executeQuery($sql, $params);
653 UPDATE civicrm_subscription_history
655 WHERE contact_id = %2
656 AND group_id IN ( $otherGroupIDString )
658 CRM_Core_DAO
::executeQuery($sql, $params);
662 SELECT cOther.group_id as group_id,
663 cOther.status as group_status
664 FROM civicrm_group_contact cMain
665 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
666 WHERE cMain.contact_id = %1
667 AND cOther.contact_id = %2
669 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
672 while ($dao->fetch()) {
673 // only copy it over if it has added status and migrate the history
674 if ($dao->group_status
== 'Added') {
675 $groupIDs[] = $dao->group_id
;
679 if (!empty($groupIDs)) {
680 $groupIDString = implode(',', $groupIDs);
683 UPDATE civicrm_group_contact
685 WHERE contact_id = %1
686 AND group_id IN ( $groupIDString )
688 CRM_Core_DAO
::executeQuery($sql, $params);
691 UPDATE civicrm_subscription_history
693 WHERE contact_id = %2
694 AND group_id IN ( $groupIDString )
696 CRM_Core_DAO
::executeQuery($sql, $params);
699 // delete all the other group contacts
702 FROM civicrm_group_contact
703 WHERE contact_id = %2
705 CRM_Core_DAO
::executeQuery($sql, $params);
709 FROM civicrm_subscription_history
710 WHERE contact_id = %2
712 CRM_Core_DAO
::executeQuery($sql, $params);
716 * Given an array of contact ids, add all the contacts to the group
718 * @param array $contactIds (reference ) the array of contact ids to be added
719 * @param int $groupId the id of the group
721 * @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);