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 (reference ) an assoc array of name/value pairs
53 * @return CRM_Contact_BAO_Group object
56 public static function add(&$params) {
58 $dataExists = self
::dataExists($params);
63 $groupContact = new CRM_Contact_BAO_GroupContact();
64 $groupContact->copyValues($params);
65 CRM_Contact_BAO_SubscriptionHistory
::create($params);
66 $groupContact->save();
71 * Check if there is data to create the object
73 * @param array $params (reference ) an assoc array of name/value pairs
78 public static function dataExists(&$params) {
79 // return if no data present
80 if ($params['group_id'] == 0) {
88 * Given the list of params in the params array, fetch the object
89 * and store the values in the values array
91 * @param array $params input parameters to find object
92 * @param array $values output values of the object
94 * @return array (reference) the values that could be potentially assigned to smarty
97 public static function getValues(&$params, &$values) {
101 $values['group']['data'] = &CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
106 // get the total count of groups
107 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
117 * Given an array of contact ids, add all the contacts to the group
119 * @param array $contactIds the array of contact ids to be added
120 * @param int $groupId the id of the group
121 * @param string $method
122 * @param string $status
123 * @param int $tracking
125 * @return array (total, added, notAdded) count of contacts added to group
128 static function addContactsToGroup(
137 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
139 list($numContactsAdded,
141 ) = self
::bulkAddContactsToGroup($contactIds,
148 // also reset the acl cache
149 $config = CRM_Core_Config
::singleton();
150 if (!$config->doNotResetCache
) {
151 CRM_ACL_BAO_Cache
::resetCache();
154 // reset the group contact cache for all group(s)
155 // if this group is being used as a smart group
156 CRM_Contact_BAO_GroupContactCache
::remove();
158 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
160 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
164 * Given an array of contact ids, remove all the contacts from the group
166 * @param array $contactIds (reference ) the array of contact ids to be removed
167 * @param int $groupId the id of the group
169 * @param string $method
170 * @param string $status
171 * @param null $tracking
173 * @return array (total, removed, notRemoved) count of contacts removed to group
176 static function removeContactsFromGroup(
183 if (!is_array($contactIds)) {
184 return array(0, 0, 0);
187 if ($status == 'Removed' ||
$status == 'Deleted') {
194 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
196 $date = date('YmdHis');
197 $numContactsRemoved = 0;
198 $numContactsNotRemoved = 0;
200 $group = new CRM_Contact_DAO_Group();
201 $group->id
= $groupId;
204 foreach ($contactIds as $contactId) {
205 if ($status == 'Deleted') {
206 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
207 $dao = CRM_Core_DAO
::executeQuery($query);
208 $historyParams = array(
209 'group_id' => $groupId,
210 'contact_id' => $contactId,
214 'tracking' => $tracking,
216 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
219 $groupContact = new CRM_Contact_DAO_GroupContact();
220 $groupContact->group_id
= $groupId;
221 $groupContact->contact_id
= $contactId;
222 // check if the selected contact id already a member, or if this is
223 // an opt-out of a smart group.
224 // if not a member remove to groupContact else keep the count of contacts that are not removed
225 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
226 // remove the contact from the group
227 $numContactsRemoved++
;
230 $numContactsNotRemoved++
;
233 //now we grant the negative membership to contact if not member. CRM-3711
234 $historyParams = array(
235 'group_id' => $groupId,
236 'contact_id' => $contactId,
240 'tracking' => $tracking,
242 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
243 $groupContact->status
= $status;
244 $groupContact->save();
248 // also reset the acl cache
249 $config = CRM_Core_Config
::singleton();
250 if (!$config->doNotResetCache
) {
251 CRM_ACL_BAO_Cache
::resetCache();
254 // reset the group contact cache for all group(s)
255 // if this group is being used as a smart group
256 CRM_Contact_BAO_GroupContactCache
::remove();
258 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
260 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
264 * Get list of all the groups and groups for a contact
266 * @param int $contactId contact id
268 * @param bool $visibility
271 * @return array $values this array has key-> group id and value group title
274 public static function getGroupList($contactId = 0, $visibility = FALSE) {
275 $group = new CRM_Contact_DAO_Group();
277 $select = $from = $where = '';
279 $select = 'SELECT DISTINCT civicrm_group.id, civicrm_group.title ';
280 $from = ' FROM civicrm_group ';
281 $where = " WHERE civicrm_group.is_active = 1 ";
283 $from .= ' , civicrm_group_contact ';
284 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
285 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
289 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
292 $orderby = " ORDER BY civicrm_group.name";
293 $sql = $select . $from . $where . $orderby;
298 while ($group->fetch()) {
299 $values[$group->id
] = $group->title
;
306 * Get the list of groups for contact based on status of group membership
308 * @param int $contactId contact id
309 * @param string $status state of membership
310 * @param int $numGroupContact number of groups for a contact that should be shown
311 * @param boolean $count true if we are interested only in the count
312 * @param boolean $ignorePermission true if we should ignore permissions for the current user
313 * useful in profile where permissions are limited for the user. If left
314 * at false only groups viewable by the current user are returned
315 * @param boolean $onlyPublicGroups true if we want to hide system groups
317 * @param bool $excludeHidden
319 * @return array (reference )|int $values the relevant data object values for the contact or
320 * the total count when $count is true
324 static function &getContactGroup(
327 $numGroupContact = NULL,
329 $ignorePermission = FALSE,
330 $onlyPublicGroups = FALSE,
331 $excludeHidden = TRUE,
335 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
339 civicrm_group_contact.id as civicrm_group_contact_id,
340 civicrm_group.title as group_title,
341 civicrm_group.visibility as visibility,
342 civicrm_group_contact.status as status,
343 civicrm_group.id as group_id,
344 civicrm_group.is_hidden as is_hidden,
345 civicrm_subscription_history.date as date,
346 civicrm_subscription_history.method as method';
349 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1 ";
351 if ($excludeHidden) {
352 $where .= " AND civicrm_group.is_hidden = 0 ";
355 $params = array(1 => array($contactId, 'Integer'));
356 if (!empty($status)) {
357 $where .= ' AND civicrm_group_contact.status = %2';
358 $params[2] = array($status, 'String');
360 if (!empty($groupId)) {
361 $where .= " AND civicrm_group.id = %3 ";
362 $params[3] = array($groupId, 'Integer');
365 'civicrm_group_contact' => 1,
366 'civicrm_group' => 1,
367 'civicrm_subscription_history' => 1,
369 $whereTables = array();
370 if ($ignorePermission) {
371 $permission = ' ( 1 ) ';
374 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
377 $from = CRM_Contact_BAO_Query
::fromClause($tables);
379 $where .= " AND $permission ";
381 if ($onlyPublicGroups) {
382 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
385 $order = $limit = '';
387 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
389 if ($numGroupContact) {
390 $limit = " LIMIT 0, $numGroupContact";
394 $sql = $select . $from . $where . $order . $limit;
397 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
401 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
403 while ($dao->fetch()) {
404 $id = $dao->civicrm_group_contact_id
;
405 $values[$id]['id'] = $id;
406 $values[$id]['group_id'] = $dao->group_id
;
407 $values[$id]['title'] = $dao->group_title
;
408 $values[$id]['visibility'] = $dao->visibility
;
409 $values[$id]['is_hidden'] = $dao->is_hidden
;
410 switch ($dao->status
) {
420 $prefix = 'pending_';
422 $values[$id][$prefix . 'date'] = $dao->date
;
423 $values[$id][$prefix . 'method'] = $dao->method
;
424 if ($status == 'Removed') {
425 $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 )";
426 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
427 if ($dateDAO->fetch()) {
428 $values[$id]['date_added'] = $dateDAO->date_added
;
437 * Returns membership details of a contact for a group
439 * @param int $contactId id of the contact
440 * @param int $groupID Id of a perticuler group
441 * @param string $method If we want the subscription history details for a specific method
443 * @return object of group contact
446 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
447 $leftJoin = $where = $orderBy = null;
450 //CRM-13341 add group_id clause
452 LEFT JOIN civicrm_subscription_history
453 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
454 AND civicrm_subscription_history.group_id = {$groupID} )";
455 $where = "AND civicrm_subscription_history.method ='Email'";
456 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
460 FROM civicrm_group_contact
462 WHERE civicrm_group_contact.contact_id = %1
463 AND civicrm_group_contact.group_id = %2
469 1 => array($contactId, 'Integer'),
470 2 => array($groupID, 'Integer'),
472 $dao = CRM_Core_DAO
::executeQuery($query, $params);
478 * Method to get Group Id
480 * @param int $groupContactID Id of a perticuler group
486 public static function getGroupId($groupContactID) {
487 $dao = new CRM_Contact_DAO_GroupContact();
488 $dao->id
= $groupContactID;
490 return $dao->group_id
;
494 * Takes an associative array and creates / removes
495 * contacts from the groups
498 * @param array $params (reference ) an assoc array of name/value pairs
499 * @param array $contactId contact id
501 * @param bool $visibility
502 * @param string $method
507 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
508 $contactIds = array();
509 $contactIds[] = $contactId;
511 //if $visibility is true we are coming in via profile mean $method = 'Web'
512 $ignorePermission = FALSE;
514 $ignorePermission = TRUE;
518 $contactGroupList = &CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
519 NULL, FALSE, $ignorePermission
521 if (is_array($contactGroupList)) {
522 foreach ($contactGroupList as $key) {
523 $groupId = $key['group_id'];
524 $contactGroup[$groupId] = $groupId;
529 // get the list of all the groups
530 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
532 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
533 if (!is_array($params)) {
537 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
538 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
539 $contactGroup = array();
542 // check which values has to be add/remove contact from group
543 foreach ($allGroup as $key => $varValue) {
544 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
545 // add contact to group
546 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
548 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
549 // remove contact from group
550 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
556 * @param int $contactID
557 * @param int $groupID
561 public static function isContactInGroup($contactID, $groupID) {
562 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
563 !CRM_Utils_Rule
::positiveInteger($groupID)
569 array('group', 'IN', array($groupID => 1), 0, 0),
570 array('contact_id', '=', $contactID, 0, 0),
572 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
574 if (!empty($contacts)) {
581 * Function merges the groups from otherContactID to mainContactID
582 * along with subscription history
584 * @param int $mainContactId contact id of main contact record.
585 * @param int $otherContactId contact id of record which is going to merge.
587 * @see CRM_Dedupe_Merger::cpTables()
589 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
594 public static function mergeGroupContact($mainContactId, $otherContactId) {
595 $params = array(1 => array($mainContactId, 'Integer'),
596 2 => array($otherContactId, 'Integer'),
599 // find all groups that are in otherContactID but not in mainContactID, copy them over
601 SELECT cOther.group_id
602 FROM civicrm_group_contact cOther
603 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
604 WHERE cOther.contact_id = %2
605 AND cMain.contact_id IS NULL
607 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
609 $otherGroupIDs = array();
610 while ($dao->fetch()) {
611 $otherGroupIDs[] = $dao->group_id
;
614 if (!empty($otherGroupIDs)) {
615 $otherGroupIDString = implode(',', $otherGroupIDs);
618 UPDATE civicrm_group_contact
620 WHERE contact_id = %2
621 AND group_id IN ( $otherGroupIDString )
623 CRM_Core_DAO
::executeQuery($sql, $params);
626 UPDATE civicrm_subscription_history
628 WHERE contact_id = %2
629 AND group_id IN ( $otherGroupIDString )
631 CRM_Core_DAO
::executeQuery($sql, $params);
635 SELECT cOther.group_id as group_id,
636 cOther.status as group_status
637 FROM civicrm_group_contact cMain
638 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
639 WHERE cMain.contact_id = %1
640 AND cOther.contact_id = %2
642 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
645 while ($dao->fetch()) {
646 // only copy it over if it has added status and migrate the history
647 if ($dao->group_status
== 'Added') {
648 $groupIDs[] = $dao->group_id
;
652 if (!empty($groupIDs)) {
653 $groupIDString = implode(',', $groupIDs);
656 UPDATE civicrm_group_contact
658 WHERE contact_id = %1
659 AND group_id IN ( $groupIDString )
661 CRM_Core_DAO
::executeQuery($sql, $params);
664 UPDATE civicrm_subscription_history
666 WHERE contact_id = %2
667 AND group_id IN ( $groupIDString )
669 CRM_Core_DAO
::executeQuery($sql, $params);
672 // delete all the other group contacts
675 FROM civicrm_group_contact
676 WHERE contact_id = %2
678 CRM_Core_DAO
::executeQuery($sql, $params);
682 FROM civicrm_subscription_history
683 WHERE contact_id = %2
685 CRM_Core_DAO
::executeQuery($sql, $params);
689 * Given an array of contact ids, add all the contacts to the group
691 * @param array $contactIDs the array of contact ids to be added
692 * @param int $groupID the id of the group
693 * @param string $method
694 * @param string $status
695 * @param null $tracking
697 * @return array (total, added, notAdded) count of contacts added to group
700 static function bulkAddContactsToGroup(
708 $numContactsAdded = 0;
709 $numContactsNotAdded = 0;
712 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
715 $subscriptioHistorySQL = "
716 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
720 $date = date('YmdHis');
722 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
723 while (!empty($contactIDs)) {
724 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
725 $contactStr = implode(',', $input);
727 // lets check their current status
729 SELECT GROUP_CONCAT(contact_id) as contactStr
730 FROM civicrm_group_contact
733 AND contact_id IN ( $contactStr )
735 $params = array(1 => array($groupID, 'Integer'),
736 2 => array($status, 'String'),
739 $presentIDs = array();
740 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
742 $presentIDs = explode(',', $dao->contactStr
);
743 $presentIDs = array_flip($presentIDs);
746 $gcValues = $shValues = array();
747 foreach ($input as $cid) {
748 if (isset($presentIDs[$cid])) {
749 $numContactsNotAdded++
;
753 $gcValues[] = "( $groupID, $cid, '$status' )";
754 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
758 if (!empty($gcValues)) {
759 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
760 CRM_Core_DAO
::executeQuery($cgSQL);
762 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
763 CRM_Core_DAO
::executeQuery($shSQL);
767 return array($numContactsAdded, $numContactsNotAdded);
771 * Get options for a given field.
772 * @see CRM_Core_DAO::buildOptions
774 * @param String $fieldName
775 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
776 * @param Array $props : whatever is known about this dao object
780 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
783 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
785 // Sort group list by hierarchy
786 // TODO: This will only work when api.entity is "group_contact". What about others?
787 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
788 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);