3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 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
96 * @internal param array $ids the array that holds all the db ids
98 * @return array (reference) the values that could be potentially assigned to smarty
102 static function getValues(&$params, &$values) {
103 if (empty($params)) {
106 $values['group']['data'] = &CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
111 // get the total count of groups
112 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
122 * Given an array of contact ids, add all the contacts to the group
124 * @param array $contactIds the array of contact ids to be added
125 * @param int $groupId the id of the group
126 * @param string $method
127 * @param string $status
128 * @param int $tracking
130 * @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 (reference ) the array of contact ids to be removed
173 * @param int $groupId the id of the group
175 * @param string $method
176 * @param string $status
177 * @param null $tracking
179 * @return array (total, removed, notRemoved) count of contacts removed to group
183 static function removeContactsFromGroup(
190 if (!is_array($contactIds)) {
191 return array(0, 0, 0);
194 if ($status == 'Removed' ||
$status == 'Deleted') {
201 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
203 $date = date('YmdHis');
204 $numContactsRemoved = 0;
205 $numContactsNotRemoved = 0;
207 $group = new CRM_Contact_DAO_Group();
208 $group->id
= $groupId;
211 foreach ($contactIds as $contactId) {
212 if ($status == 'Deleted') {
213 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
214 $dao = CRM_Core_DAO
::executeQuery($query);
215 $historyParams = array(
216 'group_id' => $groupId,
217 'contact_id' => $contactId,
221 'tracking' => $tracking,
223 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
226 $groupContact = new CRM_Contact_DAO_GroupContact();
227 $groupContact->group_id
= $groupId;
228 $groupContact->contact_id
= $contactId;
229 // check if the selected contact id already a member, or if this is
230 // an opt-out of a smart group.
231 // if not a member remove to groupContact else keep the count of contacts that are not removed
232 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
233 // remove the contact from the group
234 $numContactsRemoved++
;
237 $numContactsNotRemoved++
;
240 //now we grant the negative membership to contact if not member. CRM-3711
241 $historyParams = array(
242 'group_id' => $groupId,
243 'contact_id' => $contactId,
247 'tracking' => $tracking,
249 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
250 $groupContact->status
= $status;
251 $groupContact->save();
255 // also reset the acl cache
256 $config = CRM_Core_Config
::singleton();
257 if (!$config->doNotResetCache
) {
258 CRM_ACL_BAO_Cache
::resetCache();
261 // reset the group contact cache for all group(s)
262 // if this group is being used as a smart group
263 CRM_Contact_BAO_GroupContactCache
::remove();
265 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
267 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
271 * Function to get list of all the groups and groups for a contact
273 * @param int $contactId contact id
275 * @param bool $visibility
279 * @return array $values this array has key-> group id and value group title
282 static function getGroupList($contactId = 0, $visibility = FALSE) {
283 $group = new CRM_Contact_DAO_Group();
285 $select = $from = $where = '';
287 $select = 'SELECT DISTINCT civicrm_group.id, civicrm_group.title ';
288 $from = ' FROM civicrm_group ';
289 $where = " WHERE civicrm_group.is_active = 1 ";
291 $from .= ' , civicrm_group_contact ';
292 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
293 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
297 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
300 $orderby = " ORDER BY civicrm_group.name";
301 $sql = $select . $from . $where . $orderby;
306 while ($group->fetch()) {
307 $values[$group->id
] = $group->title
;
314 * Function to get the list of groups for contact based on status of group membership
316 * @param int $contactId contact id
317 * @param string $status state of membership
318 * @param int $numGroupContact number of groups for a contact that should be shown
319 * @param boolean $count true if we are interested only in the count
320 * @param boolean $ignorePermission true if we should ignore permissions for the current user
321 * useful in profile where permissions are limited for the user. If left
322 * at false only groups viewable by the current user are returned
323 * @param boolean $onlyPublicGroups true if we want to hide system groups
325 * @param bool $excludeHidden
327 * @return array (reference )|int $values the relevant data object values for the contact or
328 * the total count when $count is true
332 static function &getContactGroup(
335 $numGroupContact = NULL,
337 $ignorePermission = FALSE,
338 $onlyPublicGroups = FALSE,
339 $excludeHidden = TRUE
342 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
346 civicrm_group_contact.id as civicrm_group_contact_id,
347 civicrm_group.title as group_title,
348 civicrm_group.visibility as visibility,
349 civicrm_group_contact.status as status,
350 civicrm_group.id as group_id,
351 civicrm_group.is_hidden as is_hidden,
352 civicrm_subscription_history.date as date,
353 civicrm_subscription_history.method as method';
356 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1 ";
358 if ($excludeHidden) {
359 $where .= " AND civicrm_group.is_hidden = 0 ";
362 $params = array(1 => array($contactId, 'Integer'));
363 if (!empty($status)) {
364 $where .= ' AND civicrm_group_contact.status = %2';
365 $params[2] = array($status, 'String');
368 'civicrm_group_contact' => 1,
369 'civicrm_group' => 1,
370 'civicrm_subscription_history' => 1,
372 $whereTables = array();
373 if ($ignorePermission) {
374 $permission = ' ( 1 ) ';
377 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
380 $from = CRM_Contact_BAO_Query
::fromClause($tables);
382 $where .= " AND $permission ";
384 if ($onlyPublicGroups) {
385 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
388 $order = $limit = '';
390 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
392 if ($numGroupContact) {
393 $limit = " LIMIT 0, $numGroupContact";
397 $sql = $select . $from . $where . $order . $limit;
400 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
404 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
406 while ($dao->fetch()) {
407 $id = $dao->civicrm_group_contact_id
;
408 $values[$id]['id'] = $id;
409 $values[$id]['group_id'] = $dao->group_id
;
410 $values[$id]['title'] = $dao->group_title
;
411 $values[$id]['visibility'] = $dao->visibility
;
412 $values[$id]['is_hidden'] = $dao->is_hidden
;
413 switch ($dao->status
) {
423 $prefix = 'pending_';
425 $values[$id][$prefix . 'date'] = $dao->date
;
426 $values[$id][$prefix . 'method'] = $dao->method
;
427 if ($status == 'Removed') {
428 $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 )";
429 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
430 if ($dateDAO->fetch()) {
431 $values[$id]['date_added'] = $dateDAO->date_added
;
440 * Returns membership details of a contact for a group
442 * @param int $contactId id of the contact
443 * @param int $groupID Id of a perticuler group
444 * @param string $method If we want the subscription history details for a specific method
446 * @return object of group contact
450 static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
451 $leftJoin = $where = $orderBy = null;
454 //CRM-13341 add group_id clause
456 LEFT JOIN civicrm_subscription_history
457 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
458 AND civicrm_subscription_history.group_id = {$groupID} )";
459 $where = "AND civicrm_subscription_history.method ='Email'";
460 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
464 FROM civicrm_group_contact
466 WHERE civicrm_group_contact.contact_id = %1
467 AND civicrm_group_contact.group_id = %2
473 1 => array($contactId, 'Integer'),
474 2 => array($groupID, 'Integer'),
476 $dao = CRM_Core_DAO
::executeQuery($query, $params);
482 * Method to get Group Id
484 * @param int $groupContactID Id of a perticuler group
491 static function getGroupId($groupContactID) {
492 $dao = new CRM_Contact_DAO_GroupContact();
493 $dao->id
= $groupContactID;
495 return $dao->group_id
;
499 * takes an associative array and creates / removes
500 * contacts from the groups
503 * @param array $params (reference ) an assoc array of name/value pairs
504 * @param array $contactId contact id
506 * @param bool $visibility
507 * @param string $method
513 static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
514 $contactIds = array();
515 $contactIds[] = $contactId;
517 //if $visibility is true we are coming in via profile mean $method = 'Web'
518 $ignorePermission = FALSE;
520 $ignorePermission = TRUE;
524 $contactGroupList = &CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
525 NULL, FALSE, $ignorePermission
527 if (is_array($contactGroupList)) {
528 foreach ($contactGroupList as $key) {
529 $groupId = $key['group_id'];
530 $contactGroup[$groupId] = $groupId;
535 // get the list of all the groups
536 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
538 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
539 if (!is_array($params)) {
543 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
544 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
545 $contactGroup = array();
548 // check which values has to be add/remove contact from group
549 foreach ($allGroup as $key => $varValue) {
550 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
551 // add contact to group
552 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
554 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
555 // remove contact from group
556 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
567 static function isContactInGroup($contactID, $groupID) {
568 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
569 !CRM_Utils_Rule
::positiveInteger($groupID)
575 array('group', 'IN', array($groupID => 1), 0, 0),
576 array('contact_id', '=', $contactID, 0, 0),
578 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
580 if (!empty($contacts)) {
587 * Function merges the groups from otherContactID to mainContactID
588 * along with subscription history
590 * @param int $mainContactId contact id of main contact record.
591 * @param int $otherContactId contact id of record which is going to merge.
593 * @see CRM_Dedupe_Merger::cpTables()
595 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
600 static function mergeGroupContact($mainContactId, $otherContactId) {
601 $params = array(1 => array($mainContactId, 'Integer'),
602 2 => array($otherContactId, 'Integer'),
605 // find all groups that are in otherContactID but not in mainContactID, copy them over
607 SELECT cOther.group_id
608 FROM civicrm_group_contact cOther
609 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
610 WHERE cOther.contact_id = %2
611 AND cMain.contact_id IS NULL
613 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
615 $otherGroupIDs = array();
616 while ($dao->fetch()) {
617 $otherGroupIDs[] = $dao->group_id
;
620 if (!empty($otherGroupIDs)) {
621 $otherGroupIDString = implode(',', $otherGroupIDs);
624 UPDATE civicrm_group_contact
626 WHERE contact_id = %2
627 AND group_id IN ( $otherGroupIDString )
629 CRM_Core_DAO
::executeQuery($sql, $params);
632 UPDATE civicrm_subscription_history
634 WHERE contact_id = %2
635 AND group_id IN ( $otherGroupIDString )
637 CRM_Core_DAO
::executeQuery($sql, $params);
641 SELECT cOther.group_id as group_id,
642 cOther.status as group_status
643 FROM civicrm_group_contact cMain
644 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
645 WHERE cMain.contact_id = %1
646 AND cOther.contact_id = %2
648 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
651 while ($dao->fetch()) {
652 // only copy it over if it has added status and migrate the history
653 if ($dao->group_status
== 'Added') {
654 $groupIDs[] = $dao->group_id
;
658 if (!empty($groupIDs)) {
659 $groupIDString = implode(',', $groupIDs);
662 UPDATE civicrm_group_contact
664 WHERE contact_id = %1
665 AND group_id IN ( $groupIDString )
667 CRM_Core_DAO
::executeQuery($sql, $params);
670 UPDATE civicrm_subscription_history
672 WHERE contact_id = %2
673 AND group_id IN ( $groupIDString )
675 CRM_Core_DAO
::executeQuery($sql, $params);
678 // delete all the other group contacts
681 FROM civicrm_group_contact
682 WHERE contact_id = %2
684 CRM_Core_DAO
::executeQuery($sql, $params);
688 FROM civicrm_subscription_history
689 WHERE contact_id = %2
691 CRM_Core_DAO
::executeQuery($sql, $params);
695 * Given an array of contact ids, add all the contacts to the group
699 * @param string $method
700 * @param string $status
701 * @param null $tracking
702 * @internal param array $contactIds (reference ) the array of contact ids to be added
703 * @internal param int $groupId the id of the group
705 * @return array (total, added, notAdded) count of contacts added to group
709 static function bulkAddContactsToGroup(
717 $numContactsAdded = 0;
718 $numContactsNotAdded = 0;
721 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
724 $subscriptioHistorySQL = "
725 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
729 $date = date('YmdHis');
731 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
732 while (!empty($contactIDs)) {
733 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
734 $contactStr = implode(',', $input);
736 // lets check their current status
738 SELECT GROUP_CONCAT(contact_id) as contactStr
739 FROM civicrm_group_contact
742 AND contact_id IN ( $contactStr )
744 $params = array(1 => array($groupID, 'Integer'),
745 2 => array($status, 'String'),
748 $presentIDs = array();
749 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
751 $presentIDs = explode(',', $dao->contactStr
);
752 $presentIDs = array_flip($presentIDs);
755 $gcValues = $shValues = array();
756 foreach ($input as $cid) {
757 if (isset($presentIDs[$cid])) {
758 $numContactsNotAdded++
;
762 $gcValues[] = "( $groupID, $cid, '$status' )";
763 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
767 if (!empty($gcValues)) {
768 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
769 CRM_Core_DAO
::executeQuery($cgSQL);
771 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
772 CRM_Core_DAO
::executeQuery($shSQL);
776 return array($numContactsAdded, $numContactsNotAdded);