3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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
52 * (reference ) an assoc array of name/value pairs.
54 * @return CRM_Contact_BAO_Group
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
74 * (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
92 * Input parameters to find object.
93 * @param array $values
94 * Output values of the object.
97 * (reference) the values that could be potentially assigned to smarty
99 public static function getValues(&$params, &$values) {
100 if (empty($params)) {
103 $values['group']['data'] = &CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
108 // get the total count of groups
109 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'],
119 * Given an array of contact ids, add all the contacts to the group
121 * @param array $contactIds
122 * The array of contact ids to be added.
123 * @param int $groupId
124 * The id of the group.
125 * @param string $method
126 * @param string $status
127 * @param int $tracking
130 * (total, added, notAdded) count of contacts added to group
132 public static function addContactsToGroup(
140 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
142 list($numContactsAdded, $numContactsNotAdded)
143 = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
145 // also reset the acl cache
146 $config = CRM_Core_Config
::singleton();
147 if (!$config->doNotResetCache
) {
148 // HACK: Dave commented this out on 12/09/2014 due to lock wait timeouts on the acl cache that caused donations to fail.
149 //CRM_ACL_BAO_Cache::resetCache();
152 // reset the group contact cache for all group(s)
153 // if this group is being used as a smart group
154 // HACK: Dave had to disable this, too!
155 //CRM_Contact_BAO_GroupContactCache::remove();
157 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
159 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
163 * Given an array of contact ids, remove all the contacts from the group
165 * @param array $contactIds
166 * (reference ) the array of contact ids to be removed.
167 * @param int $groupId
168 * The id of the group.
170 * @param string $method
171 * @param string $status
172 * @param NULL $tracking
175 * (total, removed, notRemoved) count of contacts removed to group
177 public static function removeContactsFromGroup(
184 if (!is_array($contactIds)) {
185 return array(0, 0, 0);
188 if ($status == 'Removed' ||
$status == 'Deleted') {
195 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
197 $date = date('YmdHis');
198 $numContactsRemoved = 0;
199 $numContactsNotRemoved = 0;
201 $group = new CRM_Contact_DAO_Group();
202 $group->id
= $groupId;
205 foreach ($contactIds as $contactId) {
206 if ($status == 'Deleted') {
207 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
208 $dao = CRM_Core_DAO
::executeQuery($query);
209 $historyParams = array(
210 'group_id' => $groupId,
211 'contact_id' => $contactId,
215 'tracking' => $tracking,
217 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
220 $groupContact = new CRM_Contact_DAO_GroupContact();
221 $groupContact->group_id
= $groupId;
222 $groupContact->contact_id
= $contactId;
223 // check if the selected contact id already a member, or if this is
224 // an opt-out of a smart group.
225 // if not a member remove to groupContact else keep the count of contacts that are not removed
226 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
227 // remove the contact from the group
228 $numContactsRemoved++
;
231 $numContactsNotRemoved++
;
234 //now we grant the negative membership to contact if not member. CRM-3711
235 $historyParams = array(
236 'group_id' => $groupId,
237 'contact_id' => $contactId,
241 'tracking' => $tracking,
243 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
244 $groupContact->status
= $status;
245 $groupContact->save();
249 // also reset the acl cache
250 $config = CRM_Core_Config
::singleton();
251 if (!$config->doNotResetCache
) {
252 CRM_ACL_BAO_Cache
::resetCache();
255 // reset the group contact cache for all group(s)
256 // if this group is being used as a smart group
257 CRM_Contact_BAO_GroupContactCache
::remove();
259 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
261 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
265 * Get list of all the groups and groups for a contact.
267 * @param int $contactId
270 * @param bool $visibility
274 * this array has key-> group id and value group title
276 public static function getGroupList($contactId = 0, $visibility = FALSE) {
277 $group = new CRM_Contact_DAO_Group();
279 $select = $from = $where = '';
281 $select = 'SELECT DISTINCT civicrm_group.id, civicrm_group.title ';
282 $from = ' FROM civicrm_group ';
283 $where = " WHERE civicrm_group.is_active = 1 ";
285 $from .= ' , civicrm_group_contact ';
286 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
287 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
291 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
294 $orderby = " ORDER BY civicrm_group.name";
295 $sql = $select . $from . $where . $orderby;
300 while ($group->fetch()) {
301 $values[$group->id
] = $group->title
;
308 * Get the list of groups for contact based on status of group membership.
310 * @param int $contactId
312 * @param string $status
313 * State of membership.
314 * @param int $numGroupContact
315 * Number of groups for a contact that should be shown.
317 * True if we are interested only in the count.
318 * @param bool $ignorePermission
319 * True if we should ignore permissions for the current user.
320 * useful in profile where permissions are limited for the user. If left
321 * at false only groups viewable by the current user are returned
322 * @param bool $onlyPublicGroups
323 * True if we want to hide system groups.
325 * @param bool $excludeHidden
327 * @return array (reference)|int $values
328 * the relevant data object values for the contact or
329 * the total count when $count is TRUE
331 public static function &getContactGroup(
334 $numGroupContact = NULL,
336 $ignorePermission = FALSE,
337 $onlyPublicGroups = FALSE,
338 $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');
367 if (!empty($groupId)) {
368 $where .= " AND civicrm_group.id = %3 ";
369 $params[3] = array($groupId, 'Integer');
372 'civicrm_group_contact' => 1,
373 'civicrm_group' => 1,
374 'civicrm_subscription_history' => 1,
376 $whereTables = array();
377 if ($ignorePermission) {
378 $permission = ' ( 1 ) ';
381 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
384 $from = CRM_Contact_BAO_Query
::fromClause($tables);
386 //CRM-16945: seems hackish but as per CRM-16483 of using group criteria for Search Builder it is mandatory
387 //to include group_contact_cache clause when group table is present, so following code remove duplicacy
388 $from = str_replace("OR civicrm_group.id = civicrm_group_contact_cache.group_id", 'AND civicrm_group.saved_search_id IS NULL', $from);
390 $where .= " AND $permission ";
392 if ($onlyPublicGroups) {
393 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
396 $order = $limit = '';
398 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
400 if ($numGroupContact) {
401 $limit = " LIMIT 0, $numGroupContact";
405 $sql = $select . $from . $where . $order . $limit;
408 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
412 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
414 while ($dao->fetch()) {
415 $id = $dao->civicrm_group_contact_id
;
416 $values[$id]['id'] = $id;
417 $values[$id]['group_id'] = $dao->group_id
;
418 $values[$id]['title'] = $dao->group_title
;
419 $values[$id]['visibility'] = $dao->visibility
;
420 $values[$id]['is_hidden'] = $dao->is_hidden
;
421 switch ($dao->status
) {
431 $prefix = 'pending_';
433 $values[$id][$prefix . 'date'] = $dao->date
;
434 $values[$id][$prefix . 'method'] = $dao->method
;
435 if ($status == 'Removed') {
436 $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 )";
437 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
438 if ($dateDAO->fetch()) {
439 $values[$id]['date_added'] = $dateDAO->date_added
;
448 * Returns membership details of a contact for a group.
450 * @param int $contactId
452 * @param int $groupID
453 * Id of a perticuler group.
454 * @param string $method
455 * If we want the subscription history details for a specific method.
460 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
461 $leftJoin = $where = $orderBy = NULL;
464 //CRM-13341 add group_id clause
466 LEFT JOIN civicrm_subscription_history
467 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
468 AND civicrm_subscription_history.group_id = {$groupID} )";
469 $where = "AND civicrm_subscription_history.method ='Email'";
470 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
474 FROM civicrm_group_contact
476 WHERE civicrm_group_contact.contact_id = %1
477 AND civicrm_group_contact.group_id = %2
483 1 => array($contactId, 'Integer'),
484 2 => array($groupID, 'Integer'),
486 $dao = CRM_Core_DAO
::executeQuery($query, $params);
492 * Method to get Group Id.
494 * @param int $groupContactID
495 * Id of a perticuler group.
500 public static function getGroupId($groupContactID) {
501 $dao = new CRM_Contact_DAO_GroupContact();
502 $dao->id
= $groupContactID;
504 return $dao->group_id
;
508 * Takes an associative array and creates / removes
509 * contacts from the groups
512 * @param array $params
513 * (reference ) an assoc array of name/value pairs.
514 * @param array $contactId
517 * @param bool $visibility
518 * @param string $method
522 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
523 $contactIds = array();
524 $contactIds[] = $contactId;
526 //if $visibility is true we are coming in via profile mean $method = 'Web'
527 $ignorePermission = FALSE;
529 $ignorePermission = TRUE;
533 $contactGroupList = &CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
534 NULL, FALSE, $ignorePermission
536 if (is_array($contactGroupList)) {
537 foreach ($contactGroupList as $key) {
538 $groupId = $key['group_id'];
539 $contactGroup[$groupId] = $groupId;
544 // get the list of all the groups
545 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
547 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
548 if (!is_array($params)) {
552 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
553 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
554 $contactGroup = array();
557 // check which values has to be add/remove contact from group
558 foreach ($allGroup as $key => $varValue) {
559 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
560 // add contact to group
561 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
563 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
564 // remove contact from group
565 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
571 * @param int $contactID
572 * @param int $groupID
576 public static function isContactInGroup($contactID, $groupID) {
577 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
578 !CRM_Utils_Rule
::positiveInteger($groupID)
584 array('group', 'IN', array($groupID => 1), 0, 0),
585 array('contact_id', '=', $contactID, 0, 0),
587 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
589 if (!empty($contacts)) {
596 * Function merges the groups from otherContactID to mainContactID.
597 * along with subscription history
599 * @param int $mainContactId
600 * Contact id of main contact record.
601 * @param int $otherContactId
602 * Contact id of record which is going to merge.
604 * @see CRM_Dedupe_Merger::cpTables()
606 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
611 public static function mergeGroupContact($mainContactId, $otherContactId) {
613 1 => array($mainContactId, 'Integer'),
614 2 => array($otherContactId, 'Integer'),
617 // find all groups that are in otherContactID but not in mainContactID, copy them over
619 SELECT cOther.group_id
620 FROM civicrm_group_contact cOther
621 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
622 WHERE cOther.contact_id = %2
623 AND cMain.contact_id IS NULL
625 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
627 $otherGroupIDs = array();
628 while ($dao->fetch()) {
629 $otherGroupIDs[] = $dao->group_id
;
632 if (!empty($otherGroupIDs)) {
633 $otherGroupIDString = implode(',', $otherGroupIDs);
636 UPDATE civicrm_group_contact
638 WHERE contact_id = %2
639 AND group_id IN ( $otherGroupIDString )
641 CRM_Core_DAO
::executeQuery($sql, $params);
644 UPDATE civicrm_subscription_history
646 WHERE contact_id = %2
647 AND group_id IN ( $otherGroupIDString )
649 CRM_Core_DAO
::executeQuery($sql, $params);
653 SELECT cOther.group_id as group_id,
654 cOther.status as group_status
655 FROM civicrm_group_contact cMain
656 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
657 WHERE cMain.contact_id = %1
658 AND cOther.contact_id = %2
660 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
663 while ($dao->fetch()) {
664 // only copy it over if it has added status and migrate the history
665 if ($dao->group_status
== 'Added') {
666 $groupIDs[] = $dao->group_id
;
670 if (!empty($groupIDs)) {
671 $groupIDString = implode(',', $groupIDs);
674 UPDATE civicrm_group_contact
676 WHERE contact_id = %1
677 AND group_id IN ( $groupIDString )
679 CRM_Core_DAO
::executeQuery($sql, $params);
682 UPDATE civicrm_subscription_history
684 WHERE contact_id = %2
685 AND group_id IN ( $groupIDString )
687 CRM_Core_DAO
::executeQuery($sql, $params);
690 // delete all the other group contacts
693 FROM civicrm_group_contact
694 WHERE contact_id = %2
696 CRM_Core_DAO
::executeQuery($sql, $params);
700 FROM civicrm_subscription_history
701 WHERE contact_id = %2
703 CRM_Core_DAO
::executeQuery($sql, $params);
707 * Given an array of contact ids, add all the contacts to the group
709 * @param array $contactIDs
710 * The array of contact ids to be added.
711 * @param int $groupID
712 * The id of the group.
713 * @param string $method
714 * @param string $status
715 * @param NULL $tracking
718 * (total, added, notAdded) count of contacts added to group
720 public static function bulkAddContactsToGroup(
728 $numContactsAdded = 0;
729 $numContactsNotAdded = 0;
732 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
735 $subscriptioHistorySQL = "
736 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
740 $date = date('YmdHis');
742 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
743 while (!empty($contactIDs)) {
744 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
745 $contactStr = implode(',', $input);
747 // lets check their current status
749 SELECT GROUP_CONCAT(contact_id) as contactStr
750 FROM civicrm_group_contact
753 AND contact_id IN ( $contactStr )
756 1 => array($groupID, 'Integer'),
757 2 => array($status, 'String'),
760 $presentIDs = array();
761 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
763 $presentIDs = explode(',', $dao->contactStr
);
764 $presentIDs = array_flip($presentIDs);
767 $gcValues = $shValues = array();
768 foreach ($input as $cid) {
769 if (isset($presentIDs[$cid])) {
770 $numContactsNotAdded++
;
774 $gcValues[] = "( $groupID, $cid, '$status' )";
775 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
779 if (!empty($gcValues)) {
780 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
781 CRM_Core_DAO
::executeQuery($cgSQL);
783 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
784 CRM_Core_DAO
::executeQuery($shSQL);
788 return array($numContactsAdded, $numContactsNotAdded);
792 * Get options for a given field.
793 * @see CRM_Core_DAO::buildOptions
795 * @param string $fieldName
796 * @param string $context
797 * @see CRM_Core_DAO::buildOptionsContext
798 * @param array $props
799 * whatever is known about this dao object.
803 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
806 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
808 // Sort group list by hierarchy
809 // TODO: This will only work when api.entity is "group_contact". What about others?
810 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
811 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);