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 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 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 * @return array (reference) the values that could be potentially assigned to smarty
100 static function getValues(&$params, &$values) {
101 if (empty($params)) {
104 $values['group']['data'] = &CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
109 // get the total count of groups
110 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
120 * Given an array of contact ids, add all the contacts to the group
122 * @param array $contactIds the array of contact ids to be added
123 * @param int $groupId the id of the group
124 * @param string $method
125 * @param string $status
126 * @param int $tracking
128 * @return array (total, added, notAdded) count of contacts added to group
132 static function addContactsToGroup(
141 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
143 list($numContactsAdded,
145 ) = self
::bulkAddContactsToGroup($contactIds,
152 // also reset the acl cache
153 $config = CRM_Core_Config
::singleton();
154 if (!$config->doNotResetCache
) {
155 CRM_ACL_BAO_Cache
::resetCache();
158 // reset the group contact cache for all group(s)
159 // if this group is being used as a smart group
160 CRM_Contact_BAO_GroupContactCache
::remove();
162 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
164 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
168 * Given an array of contact ids, remove all the contacts from the group
170 * @param array $contactIds (reference ) the array of contact ids to be removed
171 * @param int $groupId the id of the group
173 * @param string $method
174 * @param string $status
175 * @param null $tracking
177 * @return array (total, removed, notRemoved) count of contacts removed to group
181 static function removeContactsFromGroup(
188 if (!is_array($contactIds)) {
189 return array(0, 0, 0);
192 if ($status == 'Removed' ||
$status == 'Deleted') {
199 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
201 $date = date('YmdHis');
202 $numContactsRemoved = 0;
203 $numContactsNotRemoved = 0;
205 $group = new CRM_Contact_DAO_Group();
206 $group->id
= $groupId;
209 foreach ($contactIds as $contactId) {
210 if ($status == 'Deleted') {
211 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
212 $dao = CRM_Core_DAO
::executeQuery($query);
213 $historyParams = array(
214 'group_id' => $groupId,
215 'contact_id' => $contactId,
219 'tracking' => $tracking,
221 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
224 $groupContact = new CRM_Contact_DAO_GroupContact();
225 $groupContact->group_id
= $groupId;
226 $groupContact->contact_id
= $contactId;
227 // check if the selected contact id already a member, or if this is
228 // an opt-out of a smart group.
229 // if not a member remove to groupContact else keep the count of contacts that are not removed
230 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
231 // remove the contact from the group
232 $numContactsRemoved++
;
235 $numContactsNotRemoved++
;
238 //now we grant the negative membership to contact if not member. CRM-3711
239 $historyParams = array(
240 'group_id' => $groupId,
241 'contact_id' => $contactId,
245 'tracking' => $tracking,
247 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
248 $groupContact->status
= $status;
249 $groupContact->save();
253 // also reset the acl cache
254 $config = CRM_Core_Config
::singleton();
255 if (!$config->doNotResetCache
) {
256 CRM_ACL_BAO_Cache
::resetCache();
259 // reset the group contact cache for all group(s)
260 // if this group is being used as a smart group
261 CRM_Contact_BAO_GroupContactCache
::remove();
263 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
265 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
269 * Get list of all the groups and groups for a contact
271 * @param int $contactId contact id
273 * @param bool $visibility
277 * @return array $values this array has key-> group id and value group title
280 static function getGroupList($contactId = 0, $visibility = FALSE) {
281 $group = new CRM_Contact_DAO_Group();
283 $select = $from = $where = '';
285 $select = 'SELECT DISTINCT civicrm_group.id, civicrm_group.title ';
286 $from = ' FROM civicrm_group ';
287 $where = " WHERE civicrm_group.is_active = 1 ";
289 $from .= ' , civicrm_group_contact ';
290 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
291 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
295 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
298 $orderby = " ORDER BY civicrm_group.name";
299 $sql = $select . $from . $where . $orderby;
304 while ($group->fetch()) {
305 $values[$group->id
] = $group->title
;
312 * Get the list of groups for contact based on status of group membership
314 * @param int $contactId contact id
315 * @param string $status state of membership
316 * @param int $numGroupContact number of groups for a contact that should be shown
317 * @param boolean $count true if we are interested only in the count
318 * @param boolean $ignorePermission true if we should ignore permissions for the current user
319 * useful in profile where permissions are limited for the user. If left
320 * at false only groups viewable by the current user are returned
321 * @param boolean $onlyPublicGroups true if we want to hide system groups
323 * @param bool $excludeHidden
325 * @return array (reference )|int $values the relevant data object values for the contact or
326 * the total count when $count is true
330 static function &getContactGroup(
333 $numGroupContact = NULL,
335 $ignorePermission = FALSE,
336 $onlyPublicGroups = FALSE,
337 $excludeHidden = TRUE,
341 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
345 civicrm_group_contact.id as civicrm_group_contact_id,
346 civicrm_group.title as group_title,
347 civicrm_group.visibility as visibility,
348 civicrm_group_contact.status as status,
349 civicrm_group.id as group_id,
350 civicrm_group.is_hidden as is_hidden,
351 civicrm_subscription_history.date as date,
352 civicrm_subscription_history.method as method';
355 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1 ";
357 if ($excludeHidden) {
358 $where .= " AND civicrm_group.is_hidden = 0 ";
361 $params = array(1 => array($contactId, 'Integer'));
362 if (!empty($status)) {
363 $where .= ' AND civicrm_group_contact.status = %2';
364 $params[2] = array($status, 'String');
366 if (!empty($groupId)) {
367 $where .= " AND civicrm_group.id = %3 ";
368 $params[3] = array($groupId, 'Integer');
371 'civicrm_group_contact' => 1,
372 'civicrm_group' => 1,
373 'civicrm_subscription_history' => 1,
375 $whereTables = array();
376 if ($ignorePermission) {
377 $permission = ' ( 1 ) ';
380 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
383 $from = CRM_Contact_BAO_Query
::fromClause($tables);
385 $where .= " AND $permission ";
387 if ($onlyPublicGroups) {
388 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
391 $order = $limit = '';
393 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
395 if ($numGroupContact) {
396 $limit = " LIMIT 0, $numGroupContact";
400 $sql = $select . $from . $where . $order . $limit;
403 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
407 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
409 while ($dao->fetch()) {
410 $id = $dao->civicrm_group_contact_id
;
411 $values[$id]['id'] = $id;
412 $values[$id]['group_id'] = $dao->group_id
;
413 $values[$id]['title'] = $dao->group_title
;
414 $values[$id]['visibility'] = $dao->visibility
;
415 $values[$id]['is_hidden'] = $dao->is_hidden
;
416 switch ($dao->status
) {
426 $prefix = 'pending_';
428 $values[$id][$prefix . 'date'] = $dao->date
;
429 $values[$id][$prefix . 'method'] = $dao->method
;
430 if ($status == 'Removed') {
431 $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 )";
432 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
433 if ($dateDAO->fetch()) {
434 $values[$id]['date_added'] = $dateDAO->date_added
;
443 * Returns membership details of a contact for a group
445 * @param int $contactId id of the contact
446 * @param int $groupID Id of a perticuler group
447 * @param string $method If we want the subscription history details for a specific method
449 * @return object of group contact
453 static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
454 $leftJoin = $where = $orderBy = null;
457 //CRM-13341 add group_id clause
459 LEFT JOIN civicrm_subscription_history
460 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
461 AND civicrm_subscription_history.group_id = {$groupID} )";
462 $where = "AND civicrm_subscription_history.method ='Email'";
463 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
467 FROM civicrm_group_contact
469 WHERE civicrm_group_contact.contact_id = %1
470 AND civicrm_group_contact.group_id = %2
476 1 => array($contactId, 'Integer'),
477 2 => array($groupID, 'Integer'),
479 $dao = CRM_Core_DAO
::executeQuery($query, $params);
485 * Method to get Group Id
487 * @param int $groupContactID Id of a perticuler group
494 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 (reference ) an assoc array of name/value pairs
507 * @param array $contactId contact id
509 * @param bool $visibility
510 * @param string $method
516 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 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 contact id of main contact record.
594 * @param int $otherContactId contact id of record which is going to merge.
596 * @see CRM_Dedupe_Merger::cpTables()
598 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
603 static function mergeGroupContact($mainContactId, $otherContactId) {
604 $params = array(1 => array($mainContactId, 'Integer'),
605 2 => array($otherContactId, 'Integer'),
608 // find all groups that are in otherContactID but not in mainContactID, copy them over
610 SELECT cOther.group_id
611 FROM civicrm_group_contact cOther
612 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
613 WHERE cOther.contact_id = %2
614 AND cMain.contact_id IS NULL
616 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
618 $otherGroupIDs = array();
619 while ($dao->fetch()) {
620 $otherGroupIDs[] = $dao->group_id
;
623 if (!empty($otherGroupIDs)) {
624 $otherGroupIDString = implode(',', $otherGroupIDs);
627 UPDATE civicrm_group_contact
629 WHERE contact_id = %2
630 AND group_id IN ( $otherGroupIDString )
632 CRM_Core_DAO
::executeQuery($sql, $params);
635 UPDATE civicrm_subscription_history
637 WHERE contact_id = %2
638 AND group_id IN ( $otherGroupIDString )
640 CRM_Core_DAO
::executeQuery($sql, $params);
644 SELECT cOther.group_id as group_id,
645 cOther.status as group_status
646 FROM civicrm_group_contact cMain
647 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
648 WHERE cMain.contact_id = %1
649 AND cOther.contact_id = %2
651 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
654 while ($dao->fetch()) {
655 // only copy it over if it has added status and migrate the history
656 if ($dao->group_status
== 'Added') {
657 $groupIDs[] = $dao->group_id
;
661 if (!empty($groupIDs)) {
662 $groupIDString = implode(',', $groupIDs);
665 UPDATE civicrm_group_contact
667 WHERE contact_id = %1
668 AND group_id IN ( $groupIDString )
670 CRM_Core_DAO
::executeQuery($sql, $params);
673 UPDATE civicrm_subscription_history
675 WHERE contact_id = %2
676 AND group_id IN ( $groupIDString )
678 CRM_Core_DAO
::executeQuery($sql, $params);
681 // delete all the other group contacts
684 FROM civicrm_group_contact
685 WHERE contact_id = %2
687 CRM_Core_DAO
::executeQuery($sql, $params);
691 FROM civicrm_subscription_history
692 WHERE contact_id = %2
694 CRM_Core_DAO
::executeQuery($sql, $params);
698 * Given an array of contact ids, add all the contacts to the group
700 * @param array $contactIDs the array of contact ids to be added
701 * @param int $groupID the id of the group
702 * @param string $method
703 * @param string $status
704 * @param null $tracking
706 * @return array (total, added, notAdded) count of contacts added to group
710 static function bulkAddContactsToGroup(
718 $numContactsAdded = 0;
719 $numContactsNotAdded = 0;
722 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
725 $subscriptioHistorySQL = "
726 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
730 $date = date('YmdHis');
732 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
733 while (!empty($contactIDs)) {
734 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
735 $contactStr = implode(',', $input);
737 // lets check their current status
739 SELECT GROUP_CONCAT(contact_id) as contactStr
740 FROM civicrm_group_contact
743 AND contact_id IN ( $contactStr )
745 $params = array(1 => array($groupID, 'Integer'),
746 2 => array($status, 'String'),
749 $presentIDs = array();
750 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
752 $presentIDs = explode(',', $dao->contactStr
);
753 $presentIDs = array_flip($presentIDs);
756 $gcValues = $shValues = array();
757 foreach ($input as $cid) {
758 if (isset($presentIDs[$cid])) {
759 $numContactsNotAdded++
;
763 $gcValues[] = "( $groupID, $cid, '$status' )";
764 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
768 if (!empty($gcValues)) {
769 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
770 CRM_Core_DAO
::executeQuery($cgSQL);
772 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
773 CRM_Core_DAO
::executeQuery($shSQL);
777 return array($numContactsAdded, $numContactsNotAdded);