3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
33 class CRM_Contact_BAO_GroupContact
extends CRM_Contact_DAO_GroupContact
{
38 public function __construct() {
39 parent
::__construct();
43 * Takes an associative array and creates a groupContact object.
45 * the function extract all the params it needs to initialize the create a
46 * group object. the params array could contain additional unused name/value
49 * @param array $params
50 * (reference ) an assoc array of name/value pairs.
52 * @return CRM_Contact_BAO_Group
54 public static function add(&$params) {
56 $dataExists = self
::dataExists($params);
61 $groupContact = new CRM_Contact_BAO_GroupContact();
62 $groupContact->copyValues($params);
63 CRM_Contact_BAO_SubscriptionHistory
::create($params);
64 $groupContact->save();
69 * Check if there is data to create the object.
71 * @param array $params
72 * (reference ) an assoc array of name/value pairs.
76 public static function dataExists(&$params) {
77 // return if no data present
78 if ($params['group_id'] == 0) {
86 * Given the list of params in the params array, fetch the object
87 * and store the values in the values array
89 * @param array $params
90 * Input parameters to find object.
91 * @param array $values
92 * Output values of the object.
95 * (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
120 * The array of contact ids to be added.
121 * @param int $groupId
122 * The id of the group.
123 * @param string $method
124 * @param string $status
125 * @param int $tracking
128 * (total, added, notAdded) count of contacts added to group
130 public static function addContactsToGroup(
138 CRM_Utils_Hook
::pre('create', 'GroupContact', $groupId, $contactIds);
140 list($numContactsAdded, $numContactsNotAdded)
141 = self
::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
143 // also reset the acl cache
144 $config = CRM_Core_Config
::singleton();
145 if (!$config->doNotResetCache
) {
146 CRM_ACL_BAO_Cache
::resetCache();
149 // reset the group contact cache for all group(s)
150 // if this group is being used as a smart group
151 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
153 CRM_Utils_Hook
::post('create', 'GroupContact', $groupId, $contactIds);
155 return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
159 * Given an array of contact ids, remove all the contacts from the group
161 * @param array $contactIds
162 * (reference ) the array of contact ids to be removed.
163 * @param int $groupId
164 * The id of the group.
166 * @param string $method
167 * @param string $status
168 * @param NULL $tracking
171 * (total, removed, notRemoved) count of contacts removed to group
173 public static function removeContactsFromGroup(
180 if (!is_array($contactIds)) {
181 return array(0, 0, 0);
184 if ($status == 'Removed' ||
$status == 'Deleted') {
191 CRM_Utils_Hook
::pre($op, 'GroupContact', $groupId, $contactIds);
193 $date = date('YmdHis');
194 $numContactsRemoved = 0;
195 $numContactsNotRemoved = 0;
197 $group = new CRM_Contact_DAO_Group();
198 $group->id
= $groupId;
201 foreach ($contactIds as $contactId) {
202 if ($status == 'Deleted') {
203 $query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
204 $dao = CRM_Core_DAO
::executeQuery($query);
205 $historyParams = array(
206 'group_id' => $groupId,
207 'contact_id' => $contactId,
211 'tracking' => $tracking,
213 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
216 $groupContact = new CRM_Contact_DAO_GroupContact();
217 $groupContact->group_id
= $groupId;
218 $groupContact->contact_id
= $contactId;
219 // check if the selected contact id already a member, or if this is
220 // an opt-out of a smart group.
221 // if not a member remove to groupContact else keep the count of contacts that are not removed
222 if ($groupContact->find(TRUE) ||
$group->saved_search_id
) {
223 // remove the contact from the group
224 $numContactsRemoved++
;
227 $numContactsNotRemoved++
;
230 //now we grant the negative membership to contact if not member. CRM-3711
231 $historyParams = array(
232 'group_id' => $groupId,
233 'contact_id' => $contactId,
237 'tracking' => $tracking,
239 CRM_Contact_BAO_SubscriptionHistory
::create($historyParams);
240 $groupContact->status
= $status;
241 $groupContact->save();
245 // also reset the acl cache
246 $config = CRM_Core_Config
::singleton();
247 if (!$config->doNotResetCache
) {
248 CRM_ACL_BAO_Cache
::resetCache();
251 // reset the group contact cache for all group(s)
252 // if this group is being used as a smart group
253 // @todo consider what to do here - it feels like we should either
254 // 1) just invalidate the specific group's cache(& perhaps any parents) & let cron do it's thing or
255 // possibly clear this specific groups cache, or just call opportunisticCacheFlush() - which would have the
256 // same effect as the remove call. The reservation about that is that it is no more aggressive for the group that
257 // we know is altered than for all the others, or perhaps, more the point with it's parents & groups that use it in
259 CRM_Contact_BAO_GroupContactCache
::remove();
261 CRM_Utils_Hook
::post($op, 'GroupContact', $groupId, $contactIds);
263 return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
267 * Get list of all the groups and groups for a contact.
269 * @param int $contactId
272 * @param bool $visibility
276 * this array has key-> group id and value group title
278 public static function getGroupList($contactId = 0, $visibility = FALSE) {
279 $group = new CRM_Contact_DAO_Group();
281 $select = $from = $where = '';
283 $select = 'SELECT DISTINCT civicrm_group.id, civicrm_group.title ';
284 $from = ' FROM civicrm_group ';
285 $where = " WHERE civicrm_group.is_active = 1 ";
287 $from .= ' , civicrm_group_contact ';
288 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
289 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type
::escape($contactId, 'Integer');
293 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
296 $orderby = " ORDER BY civicrm_group.name";
297 $sql = $select . $from . $where . $orderby;
302 while ($group->fetch()) {
303 $values[$group->id
] = $group->title
;
310 * Get the list of groups for contact based on status of group membership.
312 * @param int $contactId
314 * @param string $status
315 * State of membership.
316 * @param int $numGroupContact
317 * Number of groups for a contact that should be shown.
319 * True if we are interested only in the count.
320 * @param bool $ignorePermission
321 * True if we should ignore permissions for the current user.
322 * useful in profile where permissions are limited for the user. If left
323 * at false only groups viewable by the current user are returned
324 * @param bool $onlyPublicGroups
325 * True if we want to hide system groups.
327 * @param bool $excludeHidden
329 * @param int $groupId
331 * @return array|int $values
332 * the relevant data object values for the contact or the total count when $count is TRUE
334 public static function &getContactGroup(
337 $numGroupContact = NULL,
339 $ignorePermission = FALSE,
340 $onlyPublicGroups = FALSE,
341 $excludeHidden = TRUE,
345 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
349 civicrm_group_contact.id as civicrm_group_contact_id,
350 civicrm_group.title as group_title,
351 civicrm_group.visibility as visibility,
352 civicrm_group_contact.status as status,
353 civicrm_group.id as group_id,
354 civicrm_group.is_hidden as is_hidden,
355 civicrm_subscription_history.date as date,
356 civicrm_subscription_history.method as method';
359 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
361 if ($excludeHidden) {
362 $where .= " AND civicrm_group.is_hidden = 0 ";
365 $params = array(1 => array($contactId, 'Integer'));
366 if (!empty($status)) {
367 $where .= ' AND civicrm_group_contact.status = %2';
368 $params[2] = array($status, 'String');
370 if (!empty($groupId)) {
371 $where .= " AND civicrm_group.id = %3 ";
372 $params[3] = array($groupId, 'Integer');
375 'civicrm_group_contact' => 1,
376 'civicrm_group' => 1,
377 'civicrm_subscription_history' => 1,
379 $whereTables = array();
380 if ($ignorePermission) {
381 $permission = ' ( 1 ) ';
384 $permission = CRM_Core_Permission
::getPermissionedStaticGroupClause(CRM_Core_Permission
::VIEW
, $tables, $whereTables);
387 $from = CRM_Contact_BAO_Query
::fromClause($tables);
389 //CRM-16945: seems hackish but as per CRM-16483 of using group criteria for Search Builder it is mandatory
390 //to include group_contact_cache clause when group table is present, so following code remove duplicacy
391 $from = str_replace("OR civicrm_group.id = civicrm_group_contact_cache.group_id", 'AND civicrm_group.saved_search_id IS NULL', $from);
393 $where .= " AND $permission ";
395 if ($onlyPublicGroups) {
396 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
399 $order = $limit = '';
401 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
403 if ($numGroupContact) {
404 $limit = " LIMIT 0, $numGroupContact";
408 $sql = $select . $from . $where . $order . $limit;
411 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
415 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
417 while ($dao->fetch()) {
418 $id = $dao->civicrm_group_contact_id
;
419 $values[$id]['id'] = $id;
420 $values[$id]['group_id'] = $dao->group_id
;
421 $values[$id]['title'] = $dao->group_title
;
422 $values[$id]['visibility'] = $dao->visibility
;
423 $values[$id]['is_hidden'] = $dao->is_hidden
;
424 switch ($dao->status
) {
434 $prefix = 'pending_';
436 $values[$id][$prefix . 'date'] = $dao->date
;
437 $values[$id][$prefix . 'method'] = $dao->method
;
438 if ($status == 'Removed') {
439 $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 )";
440 $dateDAO = CRM_Core_DAO
::executeQuery($query, $params);
441 if ($dateDAO->fetch()) {
442 $values[$id]['date_added'] = $dateDAO->date_added
;
451 * Returns membership details of a contact for a group.
453 * @param int $contactId
455 * @param int $groupID
456 * Id of a particular group.
457 * @param string $method
458 * If we want the subscription history details for a specific method.
463 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
464 $leftJoin = $where = $orderBy = NULL;
467 //CRM-13341 add group_id clause
469 LEFT JOIN civicrm_subscription_history
470 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
471 AND civicrm_subscription_history.group_id = {$groupID} )";
472 $where = "AND civicrm_subscription_history.method ='Email'";
473 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
477 FROM civicrm_group_contact
479 WHERE civicrm_group_contact.contact_id = %1
480 AND civicrm_group_contact.group_id = %2
486 1 => array($contactId, 'Integer'),
487 2 => array($groupID, 'Integer'),
489 $dao = CRM_Core_DAO
::executeQuery($query, $params);
495 * Method to get Group Id.
497 * @param int $groupContactID
498 * Id of a particular group.
503 public static function getGroupId($groupContactID) {
504 $dao = new CRM_Contact_DAO_GroupContact();
505 $dao->id
= $groupContactID;
507 return $dao->group_id
;
511 * Takes an associative array and creates / removes
512 * contacts from the groups
515 * @param array $params
516 * (reference ) an assoc array of name/value pairs.
517 * @param array $contactId
520 * @param bool $visibility
521 * @param string $method
523 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
524 $contactIds = array();
525 $contactIds[] = $contactId;
527 //if $visibility is true we are coming in via profile mean $method = 'Web'
528 $ignorePermission = FALSE;
530 $ignorePermission = TRUE;
534 $contactGroupList = &CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, 'Added',
535 NULL, FALSE, $ignorePermission
537 if (is_array($contactGroupList)) {
538 foreach ($contactGroupList as $key) {
539 $groupId = $key['group_id'];
540 $contactGroup[$groupId] = $groupId;
545 // get the list of all the groups
546 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
548 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
549 if (!is_array($params)) {
553 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
554 if (!isset($contactGroup) ||
!is_array($contactGroup)) {
555 $contactGroup = array();
558 // check which values has to be add/remove contact from group
559 foreach ($allGroup as $key => $varValue) {
560 if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
561 // add contact to group
562 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
564 elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
565 // remove contact from group
566 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
572 * @param int $contactID
573 * @param int $groupID
577 public static function isContactInGroup($contactID, $groupID) {
578 if (!CRM_Utils_Rule
::positiveInteger($contactID) ||
579 !CRM_Utils_Rule
::positiveInteger($groupID)
585 array('group', 'IN', array($groupID), 0, 0),
586 array('contact_id', '=', $contactID, 0, 0),
588 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
590 if (!empty($contacts)) {
597 * Function merges the groups from otherContactID to mainContactID.
598 * along with subscription history
600 * @param int $mainContactId
601 * Contact id of main contact record.
602 * @param int $otherContactId
603 * Contact id of record which is going to merge.
605 * @see CRM_Dedupe_Merger::cpTables()
607 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
609 public static function mergeGroupContact($mainContactId, $otherContactId) {
611 1 => array($mainContactId, 'Integer'),
612 2 => array($otherContactId, 'Integer'),
615 // find all groups that are in otherContactID but not in mainContactID, copy them over
617 SELECT cOther.group_id
618 FROM civicrm_group_contact cOther
619 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
620 WHERE cOther.contact_id = %2
621 AND cMain.contact_id IS NULL
623 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
625 $otherGroupIDs = array();
626 while ($dao->fetch()) {
627 $otherGroupIDs[] = $dao->group_id
;
630 if (!empty($otherGroupIDs)) {
631 $otherGroupIDString = implode(',', $otherGroupIDs);
634 UPDATE civicrm_group_contact
636 WHERE contact_id = %2
637 AND group_id IN ( $otherGroupIDString )
639 CRM_Core_DAO
::executeQuery($sql, $params);
642 UPDATE civicrm_subscription_history
644 WHERE contact_id = %2
645 AND group_id IN ( $otherGroupIDString )
647 CRM_Core_DAO
::executeQuery($sql, $params);
651 SELECT cOther.group_id as group_id,
652 cOther.status as group_status
653 FROM civicrm_group_contact cMain
654 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
655 WHERE cMain.contact_id = %1
656 AND cOther.contact_id = %2
658 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
661 while ($dao->fetch()) {
662 // only copy it over if it has added status and migrate the history
663 if ($dao->group_status
== 'Added') {
664 $groupIDs[] = $dao->group_id
;
668 if (!empty($groupIDs)) {
669 $groupIDString = implode(',', $groupIDs);
672 UPDATE civicrm_group_contact
674 WHERE contact_id = %1
675 AND group_id IN ( $groupIDString )
677 CRM_Core_DAO
::executeQuery($sql, $params);
680 UPDATE civicrm_subscription_history
682 WHERE contact_id = %2
683 AND group_id IN ( $groupIDString )
685 CRM_Core_DAO
::executeQuery($sql, $params);
688 // delete all the other group contacts
691 FROM civicrm_group_contact
692 WHERE contact_id = %2
694 CRM_Core_DAO
::executeQuery($sql, $params);
698 FROM civicrm_subscription_history
699 WHERE contact_id = %2
701 CRM_Core_DAO
::executeQuery($sql, $params);
705 * Given an array of contact ids, add all the contacts to the group
707 * @param array $contactIDs
708 * The array of contact ids to be added.
709 * @param int $groupID
710 * The id of the group.
711 * @param string $method
712 * @param string $status
713 * @param NULL $tracking
716 * (total, added, notAdded) count of contacts added to group
718 public static function bulkAddContactsToGroup(
726 $numContactsAdded = 0;
727 $numContactsNotAdded = 0;
730 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
733 $subscriptioHistorySQL = "
734 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
738 $date = date('YmdHis');
740 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
741 while (!empty($contactIDs)) {
742 $input = array_splice($contactIDs, 0, CRM_Core_DAO
::BULK_INSERT_HIGH_COUNT
);
743 $contactStr = implode(',', $input);
745 // lets check their current status
747 SELECT GROUP_CONCAT(contact_id) as contactStr
748 FROM civicrm_group_contact
751 AND contact_id IN ( $contactStr )
754 1 => array($groupID, 'Integer'),
755 2 => array($status, 'String'),
758 $presentIDs = array();
759 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
761 $presentIDs = explode(',', $dao->contactStr
);
762 $presentIDs = array_flip($presentIDs);
765 $gcValues = $shValues = array();
766 foreach ($input as $cid) {
767 if (isset($presentIDs[$cid])) {
768 $numContactsNotAdded++
;
772 $gcValues[] = "( $groupID, $cid, '$status' )";
773 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
777 if (!empty($gcValues)) {
778 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
779 CRM_Core_DAO
::executeQuery($cgSQL);
781 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
782 CRM_Core_DAO
::executeQuery($shSQL);
786 return array($numContactsAdded, $numContactsNotAdded);
790 * Get options for a given field.
791 * @see CRM_Core_DAO::buildOptions
793 * @param string $fieldName
794 * @param string $context
795 * @see CRM_Core_DAO::buildOptionsContext
796 * @param array $props
797 * whatever is known about this dao object.
801 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
804 $options = CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
806 // Sort group list by hierarchy
807 // TODO: This will only work when api.entity is "group_contact". What about others?
808 if (($fieldName == 'group' ||
$fieldName == 'group_id') && ($context == 'search' ||
$context == 'create')) {
809 $options = CRM_Contact_BAO_Group
::getGroupsHierarchy($options, NULL, '- ', TRUE);