copyValues($params); if ($group->find(TRUE)) { CRM_Core_DAO::storeValues($group, $defaults); return $group; } } /** * Delete the group and all the object that connect to this group. * * Incredibly destructive. * * @param int $id Group id. */ public static function discard($id) { if (!$id || !is_numeric($id)) { throw new CRM_Core_Exception('Invalid group request attempted'); } CRM_Utils_Hook::pre('delete', 'Group', $id, CRM_Core_DAO::$_nullArray); $transaction = new CRM_Core_Transaction(); // added for CRM-1631 and CRM-1794 // delete all subscribed mails with the selected group id $subscribe = new CRM_Mailing_Event_DAO_Subscribe(); $subscribe->group_id = $id; $subscribe->delete(); // delete all Subscription records with the selected group id $subHistory = new CRM_Contact_DAO_SubscriptionHistory(); $subHistory->group_id = $id; $subHistory->delete(); // delete all crm_group_contact records with the selected group id $groupContact = new CRM_Contact_DAO_GroupContact(); $groupContact->group_id = $id; $groupContact->delete(); // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null $params = [1 => [$id, 'Integer']]; $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1"; CRM_Core_DAO::executeQuery($query, $params); $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1"; CRM_Core_DAO::executeQuery($query, $params); // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group // CRM-6186 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1"; CRM_Core_DAO::executeQuery($query, $params); $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1"; CRM_Core_DAO::executeQuery($query, $params); $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1"; CRM_Core_DAO::executeQuery($query, $params); // delete from group table $group = new CRM_Contact_DAO_Group(); $group->id = $id; $group->delete(); $transaction->commit(); CRM_Utils_Hook::post('delete', 'Group', $id, $group); // delete the recently created Group $groupRecent = [ 'id' => $id, 'type' => 'Group', ]; CRM_Utils_Recent::del($groupRecent); } /** * Returns an array of the contacts in the given group. * * @param int $id */ public static function getGroupContacts($id) { $params = [['group', 'IN', [1 => $id], 0, 0]]; list($contacts, $_) = CRM_Contact_BAO_Query::apiQuery($params, ['contact_id']); return $contacts; } /** * Get the count of a members in a group with the specific status. * * @param int $id * Group id. * @param string $status * status of members in group * @param bool $countChildGroups * * @return int * count of members in the group with above status */ public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) { $groupContact = new CRM_Contact_DAO_GroupContact(); $groupIds = [$id]; if ($countChildGroups) { $groupIds = CRM_Contact_BAO_GroupNesting::getDescendentGroupIds($groupIds); } $count = 0; $contacts = self::getGroupContacts($id); foreach ($groupIds as $groupId) { $groupContacts = self::getGroupContacts($groupId); foreach ($groupContacts as $gcontact) { if ($groupId != $id) { // Loop through main group's contacts // and subtract from the count for each contact which // matches one in the present group, if it is not the // main group foreach ($contacts as $contact) { if ($contact['contact_id'] == $gcontact['contact_id']) { $count--; } } } } $groupContact->group_id = $groupId; if (isset($status)) { $groupContact->status = $status; } $groupContact->_query['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)'; $count += $groupContact->count(); } return $count; } /** * Get the list of member for a group id. * * @param int $groupID * @param bool $useCache * @param int $limit * Number to limit to (or 0 for unlimited). * * @return array * this array contains the list of members for this group id */ public static function getMember($groupID, $useCache = TRUE, $limit = 0) { $params = [['group', '=', $groupID, 0, 0]]; $returnProperties = ['contact_id']; list($contacts) = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, NULL, NULL, 0, $limit, $useCache); $aMembers = []; foreach ($contacts as $contact) { $aMembers[$contact['contact_id']] = 1; } return $aMembers; } /** * Returns array of group object(s) matching a set of one or Group properties. * * @param array $params * Limits the set of groups returned. * @param array $returnProperties * Which properties should be included in the returned group objects. * (member_count should be last element.) * @param string $sort * @param int $offset * @param int $rowCount * * @return array * Array of group objects. * * * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and * add in essential fields (e.g. id). This should follow a regular pattern like the others */ public static function getGroups( $params = NULL, $returnProperties = NULL, $sort = NULL, $offset = NULL, $rowCount = NULL ) { $dao = new CRM_Contact_DAO_Group(); if (!isset($params['is_active'])) { $dao->is_active = 1; } if ($params) { foreach ($params as $k => $v) { if ($k == 'name' || $k == 'title') { $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO::escapeString($v) . '"'); } elseif ($k == 'group_type') { foreach ((array) $v as $type) { $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO::VALUE_SEPARATOR . (int) $type . CRM_Core_DAO::VALUE_SEPARATOR . "%'"); } } elseif (is_array($v)) { foreach ($v as &$num) { $num = (int) $num; } $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')'); } else { $dao->$k = $v; } } } if ($offset || $rowCount) { $offset = ($offset > 0) ? $offset : 0; $rowCount = ($rowCount > 0) ? $rowCount : 25; $dao->limit($offset, $rowCount); } if ($sort) { $dao->orderBy($sort); } // return only specific fields if returnproperties are sent if (!empty($returnProperties)) { $dao->selectAdd(); $dao->selectAdd(implode(',', $returnProperties)); } $dao->find(); $flag = $returnProperties && in_array('member_count', $returnProperties) ? 1 : 0; $groups = []; while ($dao->fetch()) { $group = new CRM_Contact_DAO_Group(); if ($flag) { $dao->member_count = CRM_Contact_BAO_Group::memberCount($dao->id); } $groups[] = clone($dao); } return $groups; } /** * Make sure that the user has permission to access this group. * * @param int $id * The id of the object. * @param bool $excludeHidden * Should hidden groups be excluded. * Logically this is the wrong place to filter hidden groups out as that is * not a permission issue. However, as other functions may rely on that defaulting to * FALSE for now & only the api call is calling with true. * * @return array * The permission that the user has (or NULL) */ public static function checkPermission($id, $excludeHidden = FALSE) { $allGroups = CRM_Core_PseudoConstant::allGroup(NULL, $excludeHidden); $permissions = NULL; if (CRM_Core_Permission::check('edit all contacts') || CRM_ACL_API::groupPermission(CRM_ACL_API::EDIT, $id, NULL, 'civicrm_saved_search', $allGroups ) ) { $permissions[] = CRM_Core_Permission::EDIT; } if (CRM_Core_Permission::check('view all contacts') || CRM_ACL_API::groupPermission(CRM_ACL_API::VIEW, $id, NULL, 'civicrm_saved_search', $allGroups ) ) { $permissions[] = CRM_Core_Permission::VIEW; } if (!empty($permissions) && CRM_Core_Permission::check('delete contacts')) { // Note: using !empty() in if condition, restricts the scope of delete // permission to groups/contacts that are editable/viewable. // We can remove this !empty condition once we have ACL support for delete functionality. $permissions[] = CRM_Core_Permission::DELETE; } return $permissions; } /** * Create a new group. * * @param array $params * * @return CRM_Contact_BAO_Group|NULL * The new group BAO (if created) */ public static function create(&$params) { if (!empty($params['id'])) { CRM_Utils_Hook::pre('edit', 'Group', $params['id'], $params); } else { CRM_Utils_Hook::pre('create', 'Group', NULL, $params); } // If title isn't specified, retrieve it because we use it later, e.g. // for RecentItems. But note we use array_key_exists not isset or empty // since otherwise there would be no way to blank out an existing title. // I'm not sure what the use-case is for that, but you're allowed to do it // currently. if (!empty($params['id']) && !array_key_exists('title', $params)) { try { $groupTitle = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $params['id'], 'title', 'id'); $params['title'] = $groupTitle; } catch (CRM_Core_Exception $groupTitleException) { // don't set title } } // dev/core#287 Disable child groups if all parents are disabled. if (!empty($params['id'])) { $allChildGroupIds = self::getChildGroupIds($params['id']); foreach ($allChildGroupIds as $childKey => $childValue) { $parentIds = CRM_Contact_BAO_GroupNesting::getParentGroupIds($childValue); $activeParentsCount = civicrm_api3('Group', 'getcount', [ 'id' => ['IN' => $parentIds], 'is_active' => 1, ]); if (count($parentIds) >= 1 && $activeParentsCount <= 1) { $setDisable = self::setIsActive($childValue, CRM_Utils_Array::value('is_active', $params, 1)); } } } // form the name only if missing: CRM-627 $nameParam = $params['name'] ?? NULL; if (!$nameParam && empty($params['id'])) { $params['name'] = CRM_Utils_String::titleToVar($params['title']); } if (!empty($params['parents'])) { $params['parents'] = CRM_Utils_Array::convertCheckboxFormatToArray((array) $params['parents']); } // convert params if array type if (isset($params['group_type'])) { $params['group_type'] = CRM_Utils_Array::convertCheckboxFormatToArray((array) $params['group_type']); } else { $params['group_type'] = NULL; } $session = CRM_Core_Session::singleton(); $cid = $session->get('userID'); // this action is add if ($cid && empty($params['id'])) { $params['created_id'] = $cid; } // this action is update if ($cid && !empty($params['id'])) { $params['modified_id'] = $cid; } // CRM-19068. // Validate parents parameter when creating group. if (!empty($params['parents'])) { $parents = is_array($params['parents']) ? array_keys($params['parents']) : (array) $params['parents']; foreach ($parents as $parent) { CRM_Utils_Type::validate($parent, 'Integer'); } } $group = new CRM_Contact_BAO_Group(); $group->copyValues($params); if (empty($params['id']) && !$nameParam ) { $group->name .= "_tmp"; } $group->save(); if (!$group->id) { return NULL; } if (empty($params['id']) && !$nameParam ) { $group->name = substr($group->name, 0, -4) . "_{$group->id}"; } $group->save(); // add custom field values if (!empty($params['custom'])) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_group', $group->id); } // make the group, child of domain/site group by default. $domainGroupID = CRM_Core_BAO_Domain::getGroupId(); if (CRM_Utils_Array::value('no_parent', $params) !== 1) { if (empty($params['parents']) && $domainGroupID != $group->id && Civi::settings()->get('is_enabled') && !CRM_Contact_BAO_GroupNesting::hasParentGroups($group->id) ) { // if no parent present and the group doesn't already have any parents, // make sure site group goes as parent $params['parents'] = [$domainGroupID]; } if (!empty($params['parents'])) { foreach ($params['parents'] as $parentId) { if ($parentId && !CRM_Contact_BAO_GroupNesting::isParentChild($parentId, $group->id)) { CRM_Contact_BAO_GroupNesting::add($parentId, $group->id); } } } // this is always required, since we don't know when a // parent group is removed CRM_Contact_BAO_GroupNestingCache::update(); // update group contact cache for all parent groups $parentIds = CRM_Contact_BAO_GroupNesting::getParentGroupIds($group->id); foreach ($parentIds as $parentId) { CRM_Contact_BAO_GroupContactCache::add($parentId); } } if (!empty($params['organization_id'])) { // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table $groupOrg = [ 'group_id' => $group->id, 'organization_id' => $params['organization_id'], ]; CRM_Contact_BAO_GroupOrganization::add($groupOrg); } self::flushCaches(); CRM_Contact_BAO_GroupContactCache::add($group->id); if (!empty($params['id'])) { CRM_Utils_Hook::post('edit', 'Group', $group->id, $group); } else { CRM_Utils_Hook::post('create', 'Group', $group->id, $group); } $recentOther = []; if (CRM_Core_Permission::check('edit groups')) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=update&id=' . $group->id); // currently same permission we are using for delete a group $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id); } // add the recently added group (unless hidden: CRM-6432) if (!$group->is_hidden) { CRM_Utils_Recent::add($group->title, CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id), $group->id, 'Group', NULL, NULL, $recentOther ); } return $group; } /** * Defines a new smart group. * * @param array $params * Associative array of parameters. * * @return CRM_Contact_BAO_Group|NULL * The new group BAO (if created) */ public static function createSmartGroup(&$params) { if (!empty($params['formValues'])) { $ssParams = $params; unset($ssParams['id']); if (isset($ssParams['saved_search_id'])) { $ssParams['id'] = $ssParams['saved_search_id']; } $params['form_values'] = $params['formValues']; $savedSearch = CRM_Contact_BAO_SavedSearch::create($params); $params['saved_search_id'] = $savedSearch->id; } else { return NULL; } return self::create($params); } /** * Update the is_active flag in the db. * * @param int $id * Id of the database record. * @param bool $isActive * Value we want to set the is_active field. * * @return bool * true if we found and updated the object, else false */ public static function setIsActive($id, $isActive) { return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive); } /** * Build the condition to retrieve groups. * * @param string $groupType * Type of group(Access/Mailing) OR the key of the group. * @param bool $excludeHidden exclude hidden groups. * * @return string */ public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) { $value = NULL; if ($groupType == 'Mailing') { $value = CRM_Core_DAO::VALUE_SEPARATOR . '2' . CRM_Core_DAO::VALUE_SEPARATOR; } elseif ($groupType == 'Access') { $value = CRM_Core_DAO::VALUE_SEPARATOR . '1' . CRM_Core_DAO::VALUE_SEPARATOR; } elseif (!empty($groupType)) { // ie we have been given the group key $value = CRM_Core_DAO::VALUE_SEPARATOR . $groupType . CRM_Core_DAO::VALUE_SEPARATOR; } $condition = NULL; if ($excludeHidden) { $condition = "is_hidden = 0"; } if ($value) { if ($condition) { $condition .= " AND group_type LIKE '%$value%'"; } else { $condition = "group_type LIKE '%$value%'"; } } return $condition; } /** * Get permission relevant clauses. * * @return array */ public static function getPermissionClause() { if (!isset(Civi::$statics[__CLASS__]['permission_clause'])) { if (CRM_Core_Permission::check('view all contacts') || CRM_Core_Permission::check('edit all contacts')) { $clause = 1; } else { //get the allowed groups for the current user $groups = CRM_ACL_API::group(CRM_ACL_API::VIEW); if (!empty($groups)) { $groupList = implode(', ', array_values($groups)); $clause = "`groups`.id IN ( $groupList ) "; } else { $clause = '1 = 0'; } } Civi::$statics[__CLASS__]['permission_clause'] = $clause; } return Civi::$statics[__CLASS__]['permission_clause']; } /** * Flush caches that hold group data. * * (Actually probably some overkill at the moment.) */ protected static function flushCaches() { CRM_Utils_System::flushCache(); $staticCaches = [ 'CRM_Core_PseudoConstant' => 'groups', 'CRM_ACL_API' => 'group_permission', 'CRM_ACL_BAO_ACL' => 'permissioned_groups', 'CRM_Contact_BAO_Group' => 'permission_clause', ]; foreach ($staticCaches as $class => $key) { if (isset(Civi::$statics[$class][$key])) { unset(Civi::$statics[$class][$key]); } } } /** * @return string */ public function __toString() { return $this->title; } /** * This function create the hidden smart group when user perform * contact search and want to send mailing to search contacts. * * @param array $params * ( reference ) an assoc array of name/value pairs. * * @return array * ( smartGroupId, ssId ) smart group id and saved search id */ public static function createHiddenSmartGroup($params) { $ssId = $params['saved_search_id'] ?? NULL; //add mapping record only for search builder saved search $mappingId = NULL; if ($params['search_context'] == 'builder') { //save the mapping for search builder if (!$ssId) { //save record in mapping table $mappingParams = [ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'), ]; $mapping = CRM_Core_BAO_Mapping::add($mappingParams); $mappingId = $mapping->id; } else { //get the mapping id from saved search $savedSearch = new CRM_Contact_BAO_SavedSearch(); $savedSearch->id = $ssId; $savedSearch->find(TRUE); $mappingId = $savedSearch->mapping_id; } //save mapping fields CRM_Core_BAO_Mapping::saveMappingFields($params['form_values'], $mappingId); } //create/update saved search record. $savedSearch = new CRM_Contact_BAO_SavedSearch(); $savedSearch->id = $ssId; $formValues = $params['search_context'] === 'builder' ? $params['form_values'] : CRM_Contact_BAO_Query::convertFormValues($params['form_values']); $savedSearch->form_values = serialize($formValues); $savedSearch->mapping_id = $mappingId; $savedSearch->search_custom_id = $params['search_custom_id'] ?? NULL; $savedSearch->save(); $ssId = $savedSearch->id; if (!$ssId) { return NULL; } $smartGroupId = NULL; if (!empty($params['saved_search_id'])) { $smartGroupId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id'); } else { //create group only when new saved search. $groupParams = [ 'title' => "Hidden Smart Group {$ssId}", 'is_active' => CRM_Utils_Array::value('is_active', $params, 1), 'is_hidden' => CRM_Utils_Array::value('is_hidden', $params, 1), 'group_type' => $params['group_type'] ?? NULL, 'visibility' => $params['visibility'] ?? NULL, 'saved_search_id' => $ssId, ]; $smartGroup = self::create($groupParams); $smartGroupId = $smartGroup->id; } // Update mapping with the name and description of the hidden smart group. if ($mappingId) { $mappingParams = [ 'id' => $mappingId, 'name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'), 'description' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'), 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'), ]; CRM_Core_BAO_Mapping::add($mappingParams); } return [$smartGroupId, $ssId]; } /** * wrapper for ajax group selector. * * @param array $params * Associated array for params record id. * * @return array * associated array of group list * -rp = rowcount * -page= offset * @todo there seems little reason for the small number of functions that call this to pass in * params that then need to be translated in this function since they are coding them when calling */ public static function getGroupListSelector(&$params) { // format the params $params['offset'] = ($params['page'] - 1) * $params['rp']; $params['rowCount'] = $params['rp']; $params['sort'] = $params['sortBy'] ?? NULL; // get groups $groups = CRM_Contact_BAO_Group::getGroupList($params); //skip total if we are making call to show only children if (empty($params['parent_id'])) { // add total $params['total'] = CRM_Contact_BAO_Group::getGroupCount($params); // get all the groups $allGroups = CRM_Core_PseudoConstant::allGroup(); } // format params and add links $groupList = []; foreach ($groups as $id => $value) { $group = []; $group['group_id'] = $value['id']; $group['count'] = $value['count']; $group['title'] = $value['title']; // append parent names if in search mode if (empty($params['parent_id']) && !empty($value['parents'])) { $group['parent_id'] = $value['parents']; $groupIds = explode(',', $value['parents']); $title = []; foreach ($groupIds as $gId) { $title[] = $allGroups[$gId]; } $group['title'] .= '