| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | CiviCRM version 5 | |
| 5 | +--------------------------------------------------------------------+ |
| 6 | | Copyright CiviCRM LLC (c) 2004-2019 | |
| 7 | +--------------------------------------------------------------------+ |
| 8 | | This file is a part of CiviCRM. | |
| 9 | | | |
| 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. | |
| 13 | | | |
| 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. | |
| 18 | | | |
| 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 | +--------------------------------------------------------------------+ |
| 26 | */ |
| 27 | |
| 28 | /** |
| 29 | * |
| 30 | * @package CRM |
| 31 | * @copyright CiviCRM LLC (c) 2004-2019 |
| 32 | */ |
| 33 | class CRM_Contact_BAO_Group extends CRM_Contact_DAO_Group { |
| 34 | |
| 35 | /** |
| 36 | * Class constructor. |
| 37 | */ |
| 38 | public function __construct() { |
| 39 | parent::__construct(); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Retrieve DB object based on input parameters. |
| 44 | * |
| 45 | * It also stores all the retrieved values in the default array. |
| 46 | * |
| 47 | * @param array $params |
| 48 | * (reference ) an assoc array of name/value pairs. |
| 49 | * @param array $defaults |
| 50 | * (reference ) an assoc array to hold the flattened values. |
| 51 | * |
| 52 | * @return CRM_Contact_BAO_Group |
| 53 | */ |
| 54 | public static function retrieve(&$params, &$defaults) { |
| 55 | $group = new CRM_Contact_DAO_Group(); |
| 56 | $group->copyValues($params); |
| 57 | if ($group->find(TRUE)) { |
| 58 | CRM_Core_DAO::storeValues($group, $defaults); |
| 59 | return $group; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Delete the group and all the object that connect to this group. |
| 65 | * |
| 66 | * Incredibly destructive. |
| 67 | * |
| 68 | * @param int $id Group id. |
| 69 | */ |
| 70 | public static function discard($id) { |
| 71 | CRM_Utils_Hook::pre('delete', 'Group', $id, CRM_Core_DAO::$_nullArray); |
| 72 | |
| 73 | $transaction = new CRM_Core_Transaction(); |
| 74 | |
| 75 | // added for CRM-1631 and CRM-1794 |
| 76 | // delete all subscribed mails with the selected group id |
| 77 | $subscribe = new CRM_Mailing_Event_DAO_Subscribe(); |
| 78 | $subscribe->group_id = $id; |
| 79 | $subscribe->delete(); |
| 80 | |
| 81 | // delete all Subscription records with the selected group id |
| 82 | $subHistory = new CRM_Contact_DAO_SubscriptionHistory(); |
| 83 | $subHistory->group_id = $id; |
| 84 | $subHistory->delete(); |
| 85 | |
| 86 | // delete all crm_group_contact records with the selected group id |
| 87 | $groupContact = new CRM_Contact_DAO_GroupContact(); |
| 88 | $groupContact->group_id = $id; |
| 89 | $groupContact->delete(); |
| 90 | |
| 91 | // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null |
| 92 | $params = [1 => [$id, 'Integer']]; |
| 93 | $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1"; |
| 94 | CRM_Core_DAO::executeQuery($query, $params); |
| 95 | |
| 96 | $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1"; |
| 97 | CRM_Core_DAO::executeQuery($query, $params); |
| 98 | |
| 99 | // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group |
| 100 | // CRM-6186 |
| 101 | $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1"; |
| 102 | CRM_Core_DAO::executeQuery($query, $params); |
| 103 | |
| 104 | $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1"; |
| 105 | CRM_Core_DAO::executeQuery($query, $params); |
| 106 | |
| 107 | $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1"; |
| 108 | CRM_Core_DAO::executeQuery($query, $params); |
| 109 | |
| 110 | // delete from group table |
| 111 | $group = new CRM_Contact_DAO_Group(); |
| 112 | $group->id = $id; |
| 113 | $group->delete(); |
| 114 | |
| 115 | $transaction->commit(); |
| 116 | |
| 117 | CRM_Utils_Hook::post('delete', 'Group', $id, $group); |
| 118 | |
| 119 | // delete the recently created Group |
| 120 | $groupRecent = [ |
| 121 | 'id' => $id, |
| 122 | 'type' => 'Group', |
| 123 | ]; |
| 124 | CRM_Utils_Recent::del($groupRecent); |
| 125 | } |
| 126 | |
| 127 | /** |
| 128 | * Returns an array of the contacts in the given group. |
| 129 | * |
| 130 | * @param int $id |
| 131 | */ |
| 132 | public static function getGroupContacts($id) { |
| 133 | $params = [['group', 'IN', [1 => $id], 0, 0]]; |
| 134 | list($contacts, $_) = CRM_Contact_BAO_Query::apiQuery($params, ['contact_id']); |
| 135 | return $contacts; |
| 136 | } |
| 137 | |
| 138 | /** |
| 139 | * Get the count of a members in a group with the specific status. |
| 140 | * |
| 141 | * @param int $id |
| 142 | * Group id. |
| 143 | * @param string $status |
| 144 | * status of members in group |
| 145 | * @param bool $countChildGroups |
| 146 | * |
| 147 | * @return int |
| 148 | * count of members in the group with above status |
| 149 | */ |
| 150 | public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) { |
| 151 | $groupContact = new CRM_Contact_DAO_GroupContact(); |
| 152 | $groupIds = [$id]; |
| 153 | if ($countChildGroups) { |
| 154 | $groupIds = CRM_Contact_BAO_GroupNesting::getDescendentGroupIds($groupIds); |
| 155 | } |
| 156 | $count = 0; |
| 157 | |
| 158 | $contacts = self::getGroupContacts($id); |
| 159 | |
| 160 | foreach ($groupIds as $groupId) { |
| 161 | |
| 162 | $groupContacts = self::getGroupContacts($groupId); |
| 163 | foreach ($groupContacts as $gcontact) { |
| 164 | if ($groupId != $id) { |
| 165 | // Loop through main group's contacts |
| 166 | // and subtract from the count for each contact which |
| 167 | // matches one in the present group, if it is not the |
| 168 | // main group |
| 169 | foreach ($contacts as $contact) { |
| 170 | if ($contact['contact_id'] == $gcontact['contact_id']) { |
| 171 | $count--; |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | $groupContact->group_id = $groupId; |
| 177 | if (isset($status)) { |
| 178 | $groupContact->status = $status; |
| 179 | } |
| 180 | $groupContact->_query['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)'; |
| 181 | $count += $groupContact->count(); |
| 182 | } |
| 183 | return $count; |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Get the list of member for a group id. |
| 188 | * |
| 189 | * @param int $groupID |
| 190 | * @param bool $useCache |
| 191 | * @param int $limit |
| 192 | * Number to limit to (or 0 for unlimited). |
| 193 | * |
| 194 | * @return array |
| 195 | * this array contains the list of members for this group id |
| 196 | */ |
| 197 | public static function getMember($groupID, $useCache = TRUE, $limit = 0) { |
| 198 | $params = [['group', '=', $groupID, 0, 0]]; |
| 199 | $returnProperties = ['contact_id']; |
| 200 | list($contacts) = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, NULL, NULL, 0, $limit, $useCache); |
| 201 | |
| 202 | $aMembers = []; |
| 203 | foreach ($contacts as $contact) { |
| 204 | $aMembers[$contact['contact_id']] = 1; |
| 205 | } |
| 206 | |
| 207 | return $aMembers; |
| 208 | } |
| 209 | |
| 210 | /** |
| 211 | * Returns array of group object(s) matching a set of one or Group properties. |
| 212 | * |
| 213 | * @param array $params |
| 214 | * Limits the set of groups returned. |
| 215 | * @param array $returnProperties |
| 216 | * Which properties should be included in the returned group objects. |
| 217 | * (member_count should be last element.) |
| 218 | * @param string $sort |
| 219 | * @param int $offset |
| 220 | * @param int $rowCount |
| 221 | * |
| 222 | * @return array |
| 223 | * Array of group objects. |
| 224 | * |
| 225 | * |
| 226 | * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and |
| 227 | * add in essential fields (e.g. id). This should follow a regular pattern like the others |
| 228 | */ |
| 229 | public static function getGroups( |
| 230 | $params = NULL, |
| 231 | $returnProperties = NULL, |
| 232 | $sort = NULL, |
| 233 | $offset = NULL, |
| 234 | $rowCount = NULL |
| 235 | ) { |
| 236 | $dao = new CRM_Contact_DAO_Group(); |
| 237 | if (!isset($params['is_active'])) { |
| 238 | $dao->is_active = 1; |
| 239 | } |
| 240 | if ($params) { |
| 241 | foreach ($params as $k => $v) { |
| 242 | if ($k == 'name' || $k == 'title') { |
| 243 | $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO::escapeString($v) . '"'); |
| 244 | } |
| 245 | elseif ($k == 'group_type') { |
| 246 | foreach ((array) $v as $type) { |
| 247 | $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO::VALUE_SEPARATOR . (int) $type . CRM_Core_DAO::VALUE_SEPARATOR . "%'"); |
| 248 | } |
| 249 | } |
| 250 | elseif (is_array($v)) { |
| 251 | foreach ($v as &$num) { |
| 252 | $num = (int) $num; |
| 253 | } |
| 254 | $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')'); |
| 255 | } |
| 256 | else { |
| 257 | $dao->$k = $v; |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | if ($offset || $rowCount) { |
| 263 | $offset = ($offset > 0) ? $offset : 0; |
| 264 | $rowCount = ($rowCount > 0) ? $rowCount : 25; |
| 265 | $dao->limit($offset, $rowCount); |
| 266 | } |
| 267 | |
| 268 | if ($sort) { |
| 269 | $dao->orderBy($sort); |
| 270 | } |
| 271 | |
| 272 | // return only specific fields if returnproperties are sent |
| 273 | if (!empty($returnProperties)) { |
| 274 | $dao->selectAdd(); |
| 275 | $dao->selectAdd(implode(',', $returnProperties)); |
| 276 | } |
| 277 | $dao->find(); |
| 278 | |
| 279 | $flag = $returnProperties && in_array('member_count', $returnProperties) ? 1 : 0; |
| 280 | |
| 281 | $groups = []; |
| 282 | while ($dao->fetch()) { |
| 283 | $group = new CRM_Contact_DAO_Group(); |
| 284 | if ($flag) { |
| 285 | $dao->member_count = CRM_Contact_BAO_Group::memberCount($dao->id); |
| 286 | } |
| 287 | $groups[] = clone($dao); |
| 288 | } |
| 289 | return $groups; |
| 290 | } |
| 291 | |
| 292 | /** |
| 293 | * Make sure that the user has permission to access this group. |
| 294 | * |
| 295 | * @param int $id |
| 296 | * The id of the object. |
| 297 | * @param bool $excludeHidden |
| 298 | * Should hidden groups be excluded. |
| 299 | * Logically this is the wrong place to filter hidden groups out as that is |
| 300 | * not a permission issue. However, as other functions may rely on that defaulting to |
| 301 | * FALSE for now & only the api call is calling with true. |
| 302 | * |
| 303 | * @return array |
| 304 | * The permission that the user has (or NULL) |
| 305 | */ |
| 306 | public static function checkPermission($id, $excludeHidden = FALSE) { |
| 307 | $allGroups = CRM_Core_PseudoConstant::allGroup(NULL, $excludeHidden); |
| 308 | |
| 309 | $permissions = NULL; |
| 310 | if (CRM_Core_Permission::check('edit all contacts') || |
| 311 | CRM_ACL_API::groupPermission(CRM_ACL_API::EDIT, $id, NULL, |
| 312 | 'civicrm_saved_search', $allGroups |
| 313 | ) |
| 314 | ) { |
| 315 | $permissions[] = CRM_Core_Permission::EDIT; |
| 316 | } |
| 317 | |
| 318 | if (CRM_Core_Permission::check('view all contacts') || |
| 319 | CRM_ACL_API::groupPermission(CRM_ACL_API::VIEW, $id, NULL, |
| 320 | 'civicrm_saved_search', $allGroups |
| 321 | ) |
| 322 | ) { |
| 323 | $permissions[] = CRM_Core_Permission::VIEW; |
| 324 | } |
| 325 | |
| 326 | if (!empty($permissions) && CRM_Core_Permission::check('delete contacts')) { |
| 327 | // Note: using !empty() in if condition, restricts the scope of delete |
| 328 | // permission to groups/contacts that are editable/viewable. |
| 329 | // We can remove this !empty condition once we have ACL support for delete functionality. |
| 330 | $permissions[] = CRM_Core_Permission::DELETE; |
| 331 | } |
| 332 | |
| 333 | return $permissions; |
| 334 | } |
| 335 | |
| 336 | /** |
| 337 | * Create a new group. |
| 338 | * |
| 339 | * @param array $params |
| 340 | * |
| 341 | * @return CRM_Contact_BAO_Group|NULL |
| 342 | * The new group BAO (if created) |
| 343 | */ |
| 344 | public static function create(&$params) { |
| 345 | |
| 346 | if (!empty($params['id'])) { |
| 347 | CRM_Utils_Hook::pre('edit', 'Group', $params['id'], $params); |
| 348 | } |
| 349 | else { |
| 350 | CRM_Utils_Hook::pre('create', 'Group', NULL, $params); |
| 351 | } |
| 352 | |
| 353 | // dev/core#287 Disable child groups if all parents are disabled. |
| 354 | if (!empty($params['id'])) { |
| 355 | $allChildGroupIds = self::getChildGroupIds($params['id']); |
| 356 | foreach ($allChildGroupIds as $childKey => $childValue) { |
| 357 | $parentIds = CRM_Contact_BAO_GroupNesting::getParentGroupIds($childValue); |
| 358 | $activeParentsCount = civicrm_api3('Group', 'getcount', [ |
| 359 | 'id' => ['IN' => $parentIds], |
| 360 | 'is_active' => 1, |
| 361 | ]); |
| 362 | if (count($parentIds) >= 1 && $activeParentsCount <= 1) { |
| 363 | $setDisable = self::setIsActive($childValue, CRM_Utils_Array::value('is_active', $params, 1)); |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | // form the name only if missing: CRM-627 |
| 368 | $nameParam = CRM_Utils_Array::value('name', $params, NULL); |
| 369 | if (!$nameParam && empty($params['id'])) { |
| 370 | $params['name'] = CRM_Utils_String::titleToVar($params['title']); |
| 371 | } |
| 372 | |
| 373 | if (!empty($params['parents'])) { |
| 374 | $params['parents'] = CRM_Utils_Array::convertCheckboxFormatToArray((array) $params['parents']); |
| 375 | } |
| 376 | |
| 377 | // convert params if array type |
| 378 | if (isset($params['group_type'])) { |
| 379 | $params['group_type'] = CRM_Utils_Array::convertCheckboxFormatToArray((array) $params['group_type']); |
| 380 | } |
| 381 | else { |
| 382 | $params['group_type'] = NULL; |
| 383 | } |
| 384 | |
| 385 | $session = CRM_Core_Session::singleton(); |
| 386 | $cid = $session->get('userID'); |
| 387 | // this action is add |
| 388 | if ($cid && empty($params['id'])) { |
| 389 | $params['created_id'] = $cid; |
| 390 | } |
| 391 | // this action is update |
| 392 | if ($cid && !empty($params['id'])) { |
| 393 | $params['modified_id'] = $cid; |
| 394 | } |
| 395 | |
| 396 | // CRM-19068. |
| 397 | // Validate parents parameter when creating group. |
| 398 | if (!empty($params['parents'])) { |
| 399 | $parents = is_array($params['parents']) ? array_keys($params['parents']) : (array) $params['parents']; |
| 400 | foreach ($parents as $parent) { |
| 401 | CRM_Utils_Type::validate($parent, 'Integer'); |
| 402 | } |
| 403 | } |
| 404 | $group = new CRM_Contact_BAO_Group(); |
| 405 | $group->copyValues($params, TRUE); |
| 406 | |
| 407 | if (empty($params['id']) && |
| 408 | !$nameParam |
| 409 | ) { |
| 410 | $group->name .= "_tmp"; |
| 411 | } |
| 412 | $group->save(); |
| 413 | |
| 414 | if (!$group->id) { |
| 415 | return NULL; |
| 416 | } |
| 417 | |
| 418 | if (empty($params['id']) && |
| 419 | !$nameParam |
| 420 | ) { |
| 421 | $group->name = substr($group->name, 0, -4) . "_{$group->id}"; |
| 422 | } |
| 423 | |
| 424 | $group->buildClause(); |
| 425 | $group->save(); |
| 426 | |
| 427 | // add custom field values |
| 428 | if (!empty($params['custom'])) { |
| 429 | CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_group', $group->id); |
| 430 | } |
| 431 | |
| 432 | // make the group, child of domain/site group by default. |
| 433 | $domainGroupID = CRM_Core_BAO_Domain::getGroupId(); |
| 434 | if (CRM_Utils_Array::value('no_parent', $params) !== 1) { |
| 435 | if (empty($params['parents']) && |
| 436 | $domainGroupID != $group->id && |
| 437 | Civi::settings()->get('is_enabled') && |
| 438 | !CRM_Contact_BAO_GroupNesting::hasParentGroups($group->id) |
| 439 | ) { |
| 440 | // if no parent present and the group doesn't already have any parents, |
| 441 | // make sure site group goes as parent |
| 442 | $params['parents'] = [$domainGroupID]; |
| 443 | } |
| 444 | |
| 445 | if (!empty($params['parents'])) { |
| 446 | foreach ($params['parents'] as $parentId) { |
| 447 | if ($parentId && !CRM_Contact_BAO_GroupNesting::isParentChild($parentId, $group->id)) { |
| 448 | CRM_Contact_BAO_GroupNesting::add($parentId, $group->id); |
| 449 | } |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | // this is always required, since we don't know when a |
| 454 | // parent group is removed |
| 455 | CRM_Contact_BAO_GroupNestingCache::update(); |
| 456 | |
| 457 | // update group contact cache for all parent groups |
| 458 | $parentIds = CRM_Contact_BAO_GroupNesting::getParentGroupIds($group->id); |
| 459 | foreach ($parentIds as $parentId) { |
| 460 | CRM_Contact_BAO_GroupContactCache::add($parentId); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | if (!empty($params['organization_id'])) { |
| 465 | // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table |
| 466 | $groupOrg = [ |
| 467 | 'group_id' => $group->id, |
| 468 | 'organization_id' => $params['organization_id'], |
| 469 | ]; |
| 470 | CRM_Contact_BAO_GroupOrganization::add($groupOrg); |
| 471 | } |
| 472 | |
| 473 | self::flushCaches(); |
| 474 | CRM_Contact_BAO_GroupContactCache::add($group->id); |
| 475 | |
| 476 | if (!empty($params['id'])) { |
| 477 | CRM_Utils_Hook::post('edit', 'Group', $group->id, $group); |
| 478 | } |
| 479 | else { |
| 480 | CRM_Utils_Hook::post('create', 'Group', $group->id, $group); |
| 481 | } |
| 482 | |
| 483 | $recentOther = []; |
| 484 | if (CRM_Core_Permission::check('edit groups')) { |
| 485 | $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=update&id=' . $group->id); |
| 486 | // currently same permission we are using for delete a group |
| 487 | $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id); |
| 488 | } |
| 489 | |
| 490 | // add the recently added group (unless hidden: CRM-6432) |
| 491 | if (!$group->is_hidden) { |
| 492 | CRM_Utils_Recent::add($group->title, |
| 493 | CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id), |
| 494 | $group->id, |
| 495 | 'Group', |
| 496 | NULL, |
| 497 | NULL, |
| 498 | $recentOther |
| 499 | ); |
| 500 | } |
| 501 | return $group; |
| 502 | } |
| 503 | |
| 504 | /** |
| 505 | * Given a saved search compute the clause and the tables |
| 506 | * and store it for future use |
| 507 | */ |
| 508 | public function buildClause() { |
| 509 | $params = [['group', 'IN', [$this->id], 0, 0]]; |
| 510 | |
| 511 | if (!empty($params)) { |
| 512 | $tables = $whereTables = []; |
| 513 | $this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables); |
| 514 | if (!empty($tables)) { |
| 515 | $this->select_tables = serialize($tables); |
| 516 | } |
| 517 | if (!empty($whereTables)) { |
| 518 | $this->where_tables = serialize($whereTables); |
| 519 | } |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | /** |
| 524 | * Defines a new smart group. |
| 525 | * |
| 526 | * @param array $params |
| 527 | * Associative array of parameters. |
| 528 | * |
| 529 | * @return CRM_Contact_BAO_Group|NULL |
| 530 | * The new group BAO (if created) |
| 531 | */ |
| 532 | public static function createSmartGroup(&$params) { |
| 533 | if (!empty($params['formValues'])) { |
| 534 | $ssParams = $params; |
| 535 | unset($ssParams['id']); |
| 536 | if (isset($ssParams['saved_search_id'])) { |
| 537 | $ssParams['id'] = $ssParams['saved_search_id']; |
| 538 | } |
| 539 | |
| 540 | $savedSearch = CRM_Contact_BAO_SavedSearch::create($params); |
| 541 | |
| 542 | $params['saved_search_id'] = $savedSearch->id; |
| 543 | } |
| 544 | else { |
| 545 | return NULL; |
| 546 | } |
| 547 | |
| 548 | return self::create($params); |
| 549 | } |
| 550 | |
| 551 | /** |
| 552 | * Update the is_active flag in the db. |
| 553 | * |
| 554 | * @param int $id |
| 555 | * Id of the database record. |
| 556 | * @param bool $isActive |
| 557 | * Value we want to set the is_active field. |
| 558 | * |
| 559 | * @return bool |
| 560 | * true if we found and updated the object, else false |
| 561 | */ |
| 562 | public static function setIsActive($id, $isActive) { |
| 563 | return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive); |
| 564 | } |
| 565 | |
| 566 | /** |
| 567 | * Build the condition to retrieve groups. |
| 568 | * |
| 569 | * @param string $groupType |
| 570 | * Type of group(Access/Mailing) OR the key of the group. |
| 571 | * @param bool $excludeHidden exclude hidden groups. |
| 572 | * |
| 573 | * @return string |
| 574 | */ |
| 575 | public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) { |
| 576 | $value = NULL; |
| 577 | if ($groupType == 'Mailing') { |
| 578 | $value = CRM_Core_DAO::VALUE_SEPARATOR . '2' . CRM_Core_DAO::VALUE_SEPARATOR; |
| 579 | } |
| 580 | elseif ($groupType == 'Access') { |
| 581 | $value = CRM_Core_DAO::VALUE_SEPARATOR . '1' . CRM_Core_DAO::VALUE_SEPARATOR; |
| 582 | } |
| 583 | elseif (!empty($groupType)) { |
| 584 | // ie we have been given the group key |
| 585 | $value = CRM_Core_DAO::VALUE_SEPARATOR . $groupType . CRM_Core_DAO::VALUE_SEPARATOR; |
| 586 | } |
| 587 | |
| 588 | $condition = NULL; |
| 589 | if ($excludeHidden) { |
| 590 | $condition = "is_hidden = 0"; |
| 591 | } |
| 592 | |
| 593 | if ($value) { |
| 594 | if ($condition) { |
| 595 | $condition .= " AND group_type LIKE '%$value%'"; |
| 596 | } |
| 597 | else { |
| 598 | $condition = "group_type LIKE '%$value%'"; |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | return $condition; |
| 603 | } |
| 604 | |
| 605 | /** |
| 606 | * Get permission relevant clauses. |
| 607 | * |
| 608 | * @return array |
| 609 | */ |
| 610 | public static function getPermissionClause() { |
| 611 | if (!isset(Civi::$statics[__CLASS__]['permission_clause'])) { |
| 612 | if (CRM_Core_Permission::check('view all contacts') || CRM_Core_Permission::check('edit all contacts')) { |
| 613 | $clause = 1; |
| 614 | } |
| 615 | else { |
| 616 | //get the allowed groups for the current user |
| 617 | $groups = CRM_ACL_API::group(CRM_ACL_API::VIEW); |
| 618 | if (!empty($groups)) { |
| 619 | $groupList = implode(', ', array_values($groups)); |
| 620 | $clause = "groups.id IN ( $groupList ) "; |
| 621 | } |
| 622 | else { |
| 623 | $clause = '1 = 0'; |
| 624 | } |
| 625 | } |
| 626 | Civi::$statics[__CLASS__]['permission_clause'] = $clause; |
| 627 | } |
| 628 | return Civi::$statics[__CLASS__]['permission_clause']; |
| 629 | } |
| 630 | |
| 631 | /** |
| 632 | * Flush caches that hold group data. |
| 633 | * |
| 634 | * (Actually probably some overkill at the moment.) |
| 635 | */ |
| 636 | protected static function flushCaches() { |
| 637 | CRM_Utils_System::flushCache(); |
| 638 | $staticCaches = [ |
| 639 | 'CRM_Core_PseudoConstant' => 'groups', |
| 640 | 'CRM_ACL_API' => 'group_permission', |
| 641 | 'CRM_ACL_BAO_ACL' => 'permissioned_groups', |
| 642 | 'CRM_Contact_BAO_Group' => 'permission_clause', |
| 643 | ]; |
| 644 | foreach ($staticCaches as $class => $key) { |
| 645 | if (isset(Civi::$statics[$class][$key])) { |
| 646 | unset(Civi::$statics[$class][$key]); |
| 647 | } |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | /** |
| 652 | * @return string |
| 653 | */ |
| 654 | public function __toString() { |
| 655 | return $this->title; |
| 656 | } |
| 657 | |
| 658 | /** |
| 659 | * This function create the hidden smart group when user perform |
| 660 | * contact search and want to send mailing to search contacts. |
| 661 | * |
| 662 | * @param array $params |
| 663 | * ( reference ) an assoc array of name/value pairs. |
| 664 | * |
| 665 | * @return array |
| 666 | * ( smartGroupId, ssId ) smart group id and saved search id |
| 667 | */ |
| 668 | public static function createHiddenSmartGroup($params) { |
| 669 | $ssId = CRM_Utils_Array::value('saved_search_id', $params); |
| 670 | |
| 671 | //add mapping record only for search builder saved search |
| 672 | $mappingId = NULL; |
| 673 | if ($params['search_context'] == 'builder') { |
| 674 | //save the mapping for search builder |
| 675 | if (!$ssId) { |
| 676 | //save record in mapping table |
| 677 | $mappingParams = [ |
| 678 | 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'), |
| 679 | ]; |
| 680 | $mapping = CRM_Core_BAO_Mapping::add($mappingParams); |
| 681 | $mappingId = $mapping->id; |
| 682 | } |
| 683 | else { |
| 684 | //get the mapping id from saved search |
| 685 | $savedSearch = new CRM_Contact_BAO_SavedSearch(); |
| 686 | $savedSearch->id = $ssId; |
| 687 | $savedSearch->find(TRUE); |
| 688 | $mappingId = $savedSearch->mapping_id; |
| 689 | } |
| 690 | |
| 691 | //save mapping fields |
| 692 | CRM_Core_BAO_Mapping::saveMappingFields($params['form_values'], $mappingId); |
| 693 | } |
| 694 | |
| 695 | //create/update saved search record. |
| 696 | $savedSearch = new CRM_Contact_BAO_SavedSearch(); |
| 697 | $savedSearch->id = $ssId; |
| 698 | $savedSearch->form_values = serialize(CRM_Contact_BAO_Query::convertFormValues($params['form_values'])); |
| 699 | $savedSearch->mapping_id = $mappingId; |
| 700 | $savedSearch->search_custom_id = CRM_Utils_Array::value('search_custom_id', $params); |
| 701 | $savedSearch->save(); |
| 702 | |
| 703 | $ssId = $savedSearch->id; |
| 704 | if (!$ssId) { |
| 705 | return NULL; |
| 706 | } |
| 707 | |
| 708 | $smartGroupId = NULL; |
| 709 | if (!empty($params['saved_search_id'])) { |
| 710 | $smartGroupId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id'); |
| 711 | } |
| 712 | else { |
| 713 | //create group only when new saved search. |
| 714 | $groupParams = [ |
| 715 | 'title' => "Hidden Smart Group {$ssId}", |
| 716 | 'is_active' => CRM_Utils_Array::value('is_active', $params, 1), |
| 717 | 'is_hidden' => CRM_Utils_Array::value('is_hidden', $params, 1), |
| 718 | 'group_type' => CRM_Utils_Array::value('group_type', $params), |
| 719 | 'visibility' => CRM_Utils_Array::value('visibility', $params), |
| 720 | 'saved_search_id' => $ssId, |
| 721 | ]; |
| 722 | |
| 723 | $smartGroup = self::create($groupParams); |
| 724 | $smartGroupId = $smartGroup->id; |
| 725 | } |
| 726 | |
| 727 | // Update mapping with the name and description of the hidden smart group. |
| 728 | if ($mappingId) { |
| 729 | $mappingParams = [ |
| 730 | 'id' => $mappingId, |
| 731 | 'name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'), |
| 732 | 'description' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'), |
| 733 | 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'), |
| 734 | ]; |
| 735 | CRM_Core_BAO_Mapping::add($mappingParams); |
| 736 | } |
| 737 | |
| 738 | return [$smartGroupId, $ssId]; |
| 739 | } |
| 740 | |
| 741 | /** |
| 742 | * wrapper for ajax group selector. |
| 743 | * |
| 744 | * @param array $params |
| 745 | * Associated array for params record id. |
| 746 | * |
| 747 | * @return array |
| 748 | * associated array of group list |
| 749 | * -rp = rowcount |
| 750 | * -page= offset |
| 751 | * @todo there seems little reason for the small number of functions that call this to pass in |
| 752 | * params that then need to be translated in this function since they are coding them when calling |
| 753 | */ |
| 754 | public static function getGroupListSelector(&$params) { |
| 755 | // format the params |
| 756 | $params['offset'] = ($params['page'] - 1) * $params['rp']; |
| 757 | $params['rowCount'] = $params['rp']; |
| 758 | $params['sort'] = CRM_Utils_Array::value('sortBy', $params); |
| 759 | |
| 760 | // get groups |
| 761 | $groups = CRM_Contact_BAO_Group::getGroupList($params); |
| 762 | |
| 763 | //skip total if we are making call to show only children |
| 764 | if (empty($params['parent_id'])) { |
| 765 | // add total |
| 766 | $params['total'] = CRM_Contact_BAO_Group::getGroupCount($params); |
| 767 | |
| 768 | // get all the groups |
| 769 | $allGroups = CRM_Core_PseudoConstant::allGroup(); |
| 770 | } |
| 771 | |
| 772 | // format params and add links |
| 773 | $groupList = []; |
| 774 | foreach ($groups as $id => $value) { |
| 775 | $group = []; |
| 776 | $group['group_id'] = $value['id']; |
| 777 | $group['count'] = $value['count']; |
| 778 | $group['title'] = $value['title']; |
| 779 | |
| 780 | // append parent names if in search mode |
| 781 | if (empty($params['parent_id']) && !empty($value['parents'])) { |
| 782 | $group['parent_id'] = $value['parents']; |
| 783 | $groupIds = explode(',', $value['parents']); |
| 784 | $title = []; |
| 785 | foreach ($groupIds as $gId) { |
| 786 | $title[] = $allGroups[$gId]; |
| 787 | } |
| 788 | $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>'; |
| 789 | $value['class'] = array_diff($value['class'], ['crm-row-parent']); |
| 790 | } |
| 791 | $group['DT_RowId'] = 'row_' . $value['id']; |
| 792 | if (empty($params['parentsOnly'])) { |
| 793 | foreach ($value['class'] as $id => $class) { |
| 794 | if ($class == 'crm-group-parent') { |
| 795 | unset($value['class'][$id]); |
| 796 | } |
| 797 | } |
| 798 | } |
| 799 | $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']); |
| 800 | $group['DT_RowAttr'] = []; |
| 801 | $group['DT_RowAttr']['data-id'] = $value['id']; |
| 802 | $group['DT_RowAttr']['data-entity'] = 'group'; |
| 803 | |
| 804 | $group['description'] = CRM_Utils_Array::value('description', $value); |
| 805 | |
| 806 | if (!empty($value['group_type'])) { |
| 807 | $group['group_type'] = $value['group_type']; |
| 808 | } |
| 809 | else { |
| 810 | $group['group_type'] = ''; |
| 811 | } |
| 812 | |
| 813 | $group['visibility'] = $value['visibility']; |
| 814 | $group['links'] = $value['action']; |
| 815 | $group['org_info'] = CRM_Utils_Array::value('org_info', $value); |
| 816 | $group['created_by'] = CRM_Utils_Array::value('created_by', $value); |
| 817 | |
| 818 | $group['is_parent'] = $value['is_parent']; |
| 819 | |
| 820 | array_push($groupList, $group); |
| 821 | } |
| 822 | |
| 823 | $groupsDT = []; |
| 824 | $groupsDT['data'] = $groupList; |
| 825 | $groupsDT['recordsTotal'] = !empty($params['total']) ? $params['total'] : NULL; |
| 826 | $groupsDT['recordsFiltered'] = !empty($params['total']) ? $params['total'] : NULL; |
| 827 | |
| 828 | return $groupsDT; |
| 829 | } |
| 830 | |
| 831 | /** |
| 832 | * This function to get list of groups. |
| 833 | * |
| 834 | * @param array $params |
| 835 | * Associated array for params. |
| 836 | * |
| 837 | * @return array |
| 838 | */ |
| 839 | public static function getGroupList(&$params) { |
| 840 | $whereClause = self::whereClause($params, FALSE); |
| 841 | |
| 842 | $limit = ""; |
| 843 | if (!empty($params['rowCount']) && |
| 844 | $params['rowCount'] > 0 |
| 845 | ) { |
| 846 | $limit = " LIMIT {$params['offset']}, {$params['rowCount']} "; |
| 847 | } |
| 848 | |
| 849 | $orderBy = ' ORDER BY groups.title asc'; |
| 850 | if (!empty($params['sort'])) { |
| 851 | $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String'); |
| 852 | |
| 853 | // CRM-16905 - Sort by count cannot be done with sql |
| 854 | if (strpos($params['sort'], 'count') === 0) { |
| 855 | $orderBy = $limit = ''; |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | $select = $from = $where = ""; |
| 860 | $groupOrg = FALSE; |
| 861 | if (CRM_Core_Permission::check('administer Multiple Organizations') && |
| 862 | CRM_Core_Permission::isMultisiteEnabled() |
| 863 | ) { |
| 864 | $select = ", contact.display_name as org_name, contact.id as org_id"; |
| 865 | $from = " LEFT JOIN civicrm_group_organization gOrg |
| 866 | ON gOrg.group_id = groups.id |
| 867 | LEFT JOIN civicrm_contact contact |
| 868 | ON contact.id = gOrg.organization_id "; |
| 869 | |
| 870 | //get the Organization ID |
| 871 | $orgID = CRM_Utils_Request::retrieve('oid', 'Positive'); |
| 872 | if ($orgID) { |
| 873 | $where = " AND gOrg.organization_id = {$orgID}"; |
| 874 | } |
| 875 | |
| 876 | $groupOrg = TRUE; |
| 877 | } |
| 878 | |
| 879 | $query = " |
| 880 | SELECT groups.*, createdBy.sort_name as created_by {$select} |
| 881 | FROM civicrm_group groups |
| 882 | LEFT JOIN civicrm_contact createdBy |
| 883 | ON createdBy.id = groups.created_id |
| 884 | {$from} |
| 885 | WHERE $whereClause {$where} |
| 886 | {$orderBy} |
| 887 | {$limit}"; |
| 888 | |
| 889 | $object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group'); |
| 890 | |
| 891 | //FIXME CRM-4418, now we are handling delete separately |
| 892 | //if we introduce 'delete for group' make sure to handle here. |
| 893 | $groupPermissions = [CRM_Core_Permission::VIEW]; |
| 894 | if (CRM_Core_Permission::check('edit groups')) { |
| 895 | $groupPermissions[] = CRM_Core_Permission::EDIT; |
| 896 | $groupPermissions[] = CRM_Core_Permission::DELETE; |
| 897 | } |
| 898 | |
| 899 | // CRM-9936 |
| 900 | $reservedPermission = CRM_Core_Permission::check('administer reserved groups'); |
| 901 | |
| 902 | $links = self::actionLinks($params); |
| 903 | |
| 904 | $allTypes = CRM_Core_OptionGroup::values('group_type'); |
| 905 | $values = []; |
| 906 | |
| 907 | $visibility = CRM_Core_SelectValues::ufVisibility(); |
| 908 | |
| 909 | while ($object->fetch()) { |
| 910 | $newLinks = $links; |
| 911 | $values[$object->id] = [ |
| 912 | 'class' => [], |
| 913 | 'count' => '0', |
| 914 | ]; |
| 915 | CRM_Core_DAO::storeValues($object, $values[$object->id]); |
| 916 | |
| 917 | if ($object->saved_search_id) { |
| 918 | $values[$object->id]['title'] .= ' (' . ts('Smart Group') . ')'; |
| 919 | // check if custom search, if so fix view link |
| 920 | $customSearchID = CRM_Core_DAO::getFieldValue( |
| 921 | 'CRM_Contact_DAO_SavedSearch', |
| 922 | $object->saved_search_id, |
| 923 | 'search_custom_id' |
| 924 | ); |
| 925 | |
| 926 | if ($customSearchID) { |
| 927 | $newLinks[CRM_Core_Action::VIEW]['url'] = 'civicrm/contact/search/custom'; |
| 928 | $newLinks[CRM_Core_Action::VIEW]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}"; |
| 929 | } |
| 930 | } |
| 931 | |
| 932 | $action = array_sum(array_keys($newLinks)); |
| 933 | |
| 934 | // CRM-9936 |
| 935 | if (array_key_exists('is_reserved', $object)) { |
| 936 | //if group is reserved and I don't have reserved permission, suppress delete/edit |
| 937 | if ($object->is_reserved && !$reservedPermission) { |
| 938 | $action -= CRM_Core_Action::DELETE; |
| 939 | $action -= CRM_Core_Action::UPDATE; |
| 940 | $action -= CRM_Core_Action::DISABLE; |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | if (array_key_exists('is_active', $object)) { |
| 945 | if ($object->is_active) { |
| 946 | $action -= CRM_Core_Action::ENABLE; |
| 947 | } |
| 948 | else { |
| 949 | $values[$object->id]['class'][] = 'disabled'; |
| 950 | $action -= CRM_Core_Action::VIEW; |
| 951 | $action -= CRM_Core_Action::DISABLE; |
| 952 | } |
| 953 | } |
| 954 | |
| 955 | $action = $action & CRM_Core_Action::mask($groupPermissions); |
| 956 | |
| 957 | $values[$object->id]['visibility'] = $visibility[$values[$object->id]['visibility']]; |
| 958 | |
| 959 | if (isset($values[$object->id]['group_type'])) { |
| 960 | $groupTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, |
| 961 | substr($values[$object->id]['group_type'], 1, -1) |
| 962 | ); |
| 963 | $types = []; |
| 964 | foreach ($groupTypes as $type) { |
| 965 | $types[] = CRM_Utils_Array::value($type, $allTypes); |
| 966 | } |
| 967 | $values[$object->id]['group_type'] = implode(', ', $types); |
| 968 | } |
| 969 | if ($action) { |
| 970 | $values[$object->id]['action'] = CRM_Core_Action::formLink($newLinks, |
| 971 | $action, |
| 972 | [ |
| 973 | 'id' => $object->id, |
| 974 | 'ssid' => $object->saved_search_id, |
| 975 | ], |
| 976 | ts('more'), |
| 977 | FALSE, |
| 978 | 'group.selector.row', |
| 979 | 'Group', |
| 980 | $object->id |
| 981 | ); |
| 982 | } |
| 983 | |
| 984 | // If group has children, add class for link to view children |
| 985 | $values[$object->id]['is_parent'] = FALSE; |
| 986 | if (array_key_exists('children', $values[$object->id])) { |
| 987 | $values[$object->id]['class'][] = "crm-group-parent"; |
| 988 | $values[$object->id]['is_parent'] = TRUE; |
| 989 | } |
| 990 | |
| 991 | // If group is a child, add child class |
| 992 | if (array_key_exists('parents', $values[$object->id])) { |
| 993 | $values[$object->id]['class'][] = "crm-group-child"; |
| 994 | } |
| 995 | |
| 996 | if ($groupOrg) { |
| 997 | if ($object->org_id) { |
| 998 | $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->org_id}"); |
| 999 | $values[$object->id]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>"; |
| 1000 | } |
| 1001 | else { |
| 1002 | // Empty cell |
| 1003 | $values[$object->id]['org_info'] = ''; |
| 1004 | } |
| 1005 | } |
| 1006 | else { |
| 1007 | // Collapsed column if all cells are NULL |
| 1008 | $values[$object->id]['org_info'] = NULL; |
| 1009 | } |
| 1010 | if ($object->created_id) { |
| 1011 | $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->created_id}"); |
| 1012 | $values[$object->id]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>"; |
| 1013 | } |
| 1014 | |
| 1015 | // By default, we try to get a count of the contacts in each group |
| 1016 | // to display to the user on the Manage Group page. However, if |
| 1017 | // that will result in the cache being regenerated, then dipslay |
| 1018 | // "unknown" instead to avoid a long wait for the user. |
| 1019 | if (CRM_Contact_BAO_GroupContactCache::shouldGroupBeRefreshed($object->id)) { |
| 1020 | $values[$object->id]['count'] = ts('unknown'); |
| 1021 | } |
| 1022 | else { |
| 1023 | $values[$object->id]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id]); |
| 1024 | } |
| 1025 | } |
| 1026 | |
| 1027 | // CRM-16905 - Sort by count cannot be done with sql |
| 1028 | if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) { |
| 1029 | usort($values, function($a, $b) { |
| 1030 | return $a['count'] - $b['count']; |
| 1031 | }); |
| 1032 | if (strpos($params['sort'], 'desc')) { |
| 1033 | $values = array_reverse($values, TRUE); |
| 1034 | } |
| 1035 | return array_slice($values, $params['offset'], $params['rowCount']); |
| 1036 | } |
| 1037 | |
| 1038 | return $values; |
| 1039 | } |
| 1040 | |
| 1041 | /** |
| 1042 | * This function to get hierarchical list of groups (parent followed by children) |
| 1043 | * |
| 1044 | * @param array $groupIDs |
| 1045 | * Array of group ids. |
| 1046 | * |
| 1047 | * @param string $parents |
| 1048 | * @param string $spacer |
| 1049 | * @param bool $titleOnly |
| 1050 | * |
| 1051 | * @return array |
| 1052 | */ |
| 1053 | public static function getGroupsHierarchy( |
| 1054 | $groupIDs, |
| 1055 | $parents = NULL, |
| 1056 | $spacer = '<span class="child-indent"></span>', |
| 1057 | $titleOnly = FALSE |
| 1058 | ) { |
| 1059 | if (empty($groupIDs)) { |
| 1060 | return []; |
| 1061 | } |
| 1062 | |
| 1063 | $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')'; |
| 1064 | // <span class="child-icon"></span> |
| 1065 | // need to return id, title (w/ spacer), description, visibility |
| 1066 | |
| 1067 | // We need to build a list of tags ordered by hierarchy and sorted by |
| 1068 | // name. The hierarchy will be communicated by an accumulation of |
| 1069 | // separators in front of the name to give it a visual offset. |
| 1070 | // Instead of recursively making mysql queries, we'll make one big |
| 1071 | // query and build the hierarchy with the algorithm below. |
| 1072 | $groups = []; |
| 1073 | $args = [1 => [$groupIdString, 'String']]; |
| 1074 | $query = " |
| 1075 | SELECT id, title, description, visibility, parents |
| 1076 | FROM civicrm_group |
| 1077 | WHERE id IN $groupIdString |
| 1078 | "; |
| 1079 | if ($parents) { |
| 1080 | // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). |
| 1081 | $parentArray = explode(',', $parents); |
| 1082 | $parent = self::filterActiveGroups($parentArray); |
| 1083 | $args[2] = [$parent, 'Integer']; |
| 1084 | $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2"; |
| 1085 | } |
| 1086 | $query .= " ORDER BY title"; |
| 1087 | $dao = CRM_Core_DAO::executeQuery($query, $args); |
| 1088 | |
| 1089 | // Sort the groups into the correct storage by the parent |
| 1090 | // $roots represent the current leaf nodes that need to be checked for |
| 1091 | // children. $rows represent the unplaced nodes |
| 1092 | // $tree contains the child nodes based on their parent_id. |
| 1093 | $roots = []; |
| 1094 | $tree = []; |
| 1095 | while ($dao->fetch()) { |
| 1096 | if ($dao->parents) { |
| 1097 | $parentArray = explode(',', $dao->parents); |
| 1098 | $parent = self::filterActiveGroups($parentArray); |
| 1099 | $tree[$parent][] = [ |
| 1100 | 'id' => $dao->id, |
| 1101 | 'title' => $dao->title, |
| 1102 | 'visibility' => $dao->visibility, |
| 1103 | 'description' => $dao->description, |
| 1104 | ]; |
| 1105 | } |
| 1106 | else { |
| 1107 | $roots[] = [ |
| 1108 | 'id' => $dao->id, |
| 1109 | 'title' => $dao->title, |
| 1110 | 'visibility' => $dao->visibility, |
| 1111 | 'description' => $dao->description, |
| 1112 | ]; |
| 1113 | } |
| 1114 | } |
| 1115 | |
| 1116 | $hierarchy = []; |
| 1117 | for ($i = 0; $i < count($roots); $i++) { |
| 1118 | self::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0); |
| 1119 | } |
| 1120 | return $hierarchy; |
| 1121 | } |
| 1122 | |
| 1123 | /** |
| 1124 | * Build a list with groups on alphabetical order and child groups after the parent group. |
| 1125 | * |
| 1126 | * This is a recursive function filling the $hierarchy parameter. |
| 1127 | * |
| 1128 | * @param $hierarchy |
| 1129 | * @param $group |
| 1130 | * @param $tree |
| 1131 | * @param $titleOnly |
| 1132 | * @param $spacer |
| 1133 | * @param $level |
| 1134 | */ |
| 1135 | private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) { |
| 1136 | $spaces = str_repeat($spacer, $level); |
| 1137 | |
| 1138 | if ($titleOnly) { |
| 1139 | $hierarchy[$group['id']] = $spaces . $group['title']; |
| 1140 | } |
| 1141 | else { |
| 1142 | $hierarchy[$group['id']] = [ |
| 1143 | 'title' => $spaces . $group['title'], |
| 1144 | 'description' => $group['description'], |
| 1145 | 'visibility' => $group['visibility'], |
| 1146 | ]; |
| 1147 | } |
| 1148 | |
| 1149 | // For performance reasons we use a for loop rather than a foreach. |
| 1150 | // Metrics for performance in an installation with 2867 groups a foreach |
| 1151 | // caused the function getGroupsHierarchy with a foreach execution takes |
| 1152 | // around 2.2 seoonds (2,200 ms). |
| 1153 | // Changing to a for loop execustion takes around 0.02 seconds (20 ms). |
| 1154 | if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) { |
| 1155 | for ($i = 0; $i < count($tree[$group['id']]); $i++) { |
| 1156 | self::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level + 1); |
| 1157 | } |
| 1158 | } |
| 1159 | } |
| 1160 | |
| 1161 | /** |
| 1162 | * @param array $params |
| 1163 | * |
| 1164 | * @return NULL|string |
| 1165 | */ |
| 1166 | public static function getGroupCount(&$params) { |
| 1167 | $whereClause = self::whereClause($params, FALSE); |
| 1168 | $query = "SELECT COUNT(*) FROM civicrm_group groups"; |
| 1169 | |
| 1170 | if (!empty($params['created_by'])) { |
| 1171 | $query .= " |
| 1172 | INNER JOIN civicrm_contact createdBy |
| 1173 | ON createdBy.id = groups.created_id"; |
| 1174 | } |
| 1175 | $query .= " |
| 1176 | WHERE {$whereClause}"; |
| 1177 | return CRM_Core_DAO::singleValueQuery($query, $params); |
| 1178 | } |
| 1179 | |
| 1180 | /** |
| 1181 | * Generate permissioned where clause for group search. |
| 1182 | * @param array $params |
| 1183 | * @param bool $sortBy |
| 1184 | * @param bool $excludeHidden |
| 1185 | * |
| 1186 | * @return string |
| 1187 | */ |
| 1188 | public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) { |
| 1189 | $values = []; |
| 1190 | $title = CRM_Utils_Array::value('title', $params); |
| 1191 | if ($title) { |
| 1192 | $clauses[] = "groups.title LIKE %1"; |
| 1193 | if (strpos($title, '%') !== FALSE) { |
| 1194 | $params[1] = [$title, 'String', FALSE]; |
| 1195 | } |
| 1196 | else { |
| 1197 | $params[1] = [$title, 'String', TRUE]; |
| 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | $groupType = CRM_Utils_Array::value('group_type', $params); |
| 1202 | if ($groupType) { |
| 1203 | $types = explode(',', $groupType); |
| 1204 | if (!empty($types)) { |
| 1205 | $clauses[] = 'groups.group_type LIKE %2'; |
| 1206 | $typeString = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $types) . CRM_Core_DAO::VALUE_SEPARATOR; |
| 1207 | $params[2] = [$typeString, 'String', TRUE]; |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | $visibility = CRM_Utils_Array::value('visibility', $params); |
| 1212 | if ($visibility) { |
| 1213 | $clauses[] = 'groups.visibility = %3'; |
| 1214 | $params[3] = [$visibility, 'String']; |
| 1215 | } |
| 1216 | |
| 1217 | $groupStatus = CRM_Utils_Array::value('status', $params); |
| 1218 | if ($groupStatus) { |
| 1219 | switch ($groupStatus) { |
| 1220 | case 1: |
| 1221 | $clauses[] = 'groups.is_active = 1'; |
| 1222 | $params[4] = [$groupStatus, 'Integer']; |
| 1223 | break; |
| 1224 | |
| 1225 | case 2: |
| 1226 | $clauses[] = 'groups.is_active = 0'; |
| 1227 | $params[4] = [$groupStatus, 'Integer']; |
| 1228 | break; |
| 1229 | |
| 1230 | case 3: |
| 1231 | $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )'; |
| 1232 | break; |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | $parentsOnly = CRM_Utils_Array::value('parentsOnly', $params); |
| 1237 | if ($parentsOnly) { |
| 1238 | $clauses[] = 'groups.parents IS NULL'; |
| 1239 | } |
| 1240 | |
| 1241 | // only show child groups of a specific parent group |
| 1242 | $parent_id = CRM_Utils_Array::value('parent_id', $params); |
| 1243 | if ($parent_id) { |
| 1244 | $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)'; |
| 1245 | $params[5] = [$parent_id, 'Integer']; |
| 1246 | } |
| 1247 | |
| 1248 | if ($createdBy = CRM_Utils_Array::value('created_by', $params)) { |
| 1249 | $clauses[] = "createdBy.sort_name LIKE %6"; |
| 1250 | if (strpos($createdBy, '%') !== FALSE) { |
| 1251 | $params[6] = [$createdBy, 'String', FALSE]; |
| 1252 | } |
| 1253 | else { |
| 1254 | $params[6] = [$createdBy, 'String', TRUE]; |
| 1255 | } |
| 1256 | } |
| 1257 | |
| 1258 | if (empty($clauses)) { |
| 1259 | $clauses[] = 'groups.is_active = 1'; |
| 1260 | } |
| 1261 | |
| 1262 | if ($excludeHidden) { |
| 1263 | $clauses[] = 'groups.is_hidden = 0'; |
| 1264 | } |
| 1265 | |
| 1266 | $clauses[] = self::getPermissionClause(); |
| 1267 | |
| 1268 | return implode(' AND ', $clauses); |
| 1269 | } |
| 1270 | |
| 1271 | /** |
| 1272 | * Define action links. |
| 1273 | * |
| 1274 | * @return array |
| 1275 | * array of action links |
| 1276 | */ |
| 1277 | public static function actionLinks($params) { |
| 1278 | // If component_mode is set we change the "View" link to match the requested component type |
| 1279 | if (!isset($params['component_mode'])) { |
| 1280 | $params['component_mode'] = CRM_Contact_BAO_Query::MODE_CONTACTS; |
| 1281 | } |
| 1282 | $modeValue = CRM_Contact_Form_Search::getModeValue($params['component_mode']); |
| 1283 | $links = [ |
| 1284 | CRM_Core_Action::VIEW => [ |
| 1285 | 'name' => $modeValue['selectorLabel'], |
| 1286 | 'url' => 'civicrm/group/search', |
| 1287 | 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'], |
| 1288 | 'title' => ts('Group Contacts'), |
| 1289 | ], |
| 1290 | CRM_Core_Action::UPDATE => [ |
| 1291 | 'name' => ts('Settings'), |
| 1292 | 'url' => 'civicrm/group', |
| 1293 | 'qs' => 'reset=1&action=update&id=%%id%%', |
| 1294 | 'title' => ts('Edit Group'), |
| 1295 | ], |
| 1296 | CRM_Core_Action::DISABLE => [ |
| 1297 | 'name' => ts('Disable'), |
| 1298 | 'ref' => 'crm-enable-disable', |
| 1299 | 'title' => ts('Disable Group'), |
| 1300 | ], |
| 1301 | CRM_Core_Action::ENABLE => [ |
| 1302 | 'name' => ts('Enable'), |
| 1303 | 'ref' => 'crm-enable-disable', |
| 1304 | 'title' => ts('Enable Group'), |
| 1305 | ], |
| 1306 | CRM_Core_Action::DELETE => [ |
| 1307 | 'name' => ts('Delete'), |
| 1308 | 'url' => 'civicrm/group', |
| 1309 | 'qs' => 'reset=1&action=delete&id=%%id%%', |
| 1310 | 'title' => ts('Delete Group'), |
| 1311 | ], |
| 1312 | ]; |
| 1313 | |
| 1314 | return $links; |
| 1315 | } |
| 1316 | |
| 1317 | /** |
| 1318 | * @param $whereClause |
| 1319 | * @param array $whereParams |
| 1320 | * |
| 1321 | * @return string |
| 1322 | */ |
| 1323 | public function pagerAtoZ($whereClause, $whereParams) { |
| 1324 | $query = " |
| 1325 | SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name |
| 1326 | FROM civicrm_group groups |
| 1327 | WHERE $whereClause |
| 1328 | ORDER BY LEFT(groups.title, 1) |
| 1329 | "; |
| 1330 | $dao = CRM_Core_DAO::executeQuery($query, $whereParams); |
| 1331 | |
| 1332 | return CRM_Utils_PagerAToZ::getAToZBar($dao, $this->_sortByCharacter, TRUE); |
| 1333 | } |
| 1334 | |
| 1335 | /** |
| 1336 | * Assign Test Value. |
| 1337 | * |
| 1338 | * @param string $fieldName |
| 1339 | * @param array $fieldDef |
| 1340 | * @param int $counter |
| 1341 | */ |
| 1342 | protected function assignTestValue($fieldName, &$fieldDef, $counter) { |
| 1343 | if ($fieldName == 'children' || $fieldName == 'parents') { |
| 1344 | $this->{$fieldName} = "NULL"; |
| 1345 | } |
| 1346 | else { |
| 1347 | parent::assignTestValues($fieldName, $fieldDef, $counter); |
| 1348 | } |
| 1349 | } |
| 1350 | |
| 1351 | /** |
| 1352 | * Get child group ids |
| 1353 | * |
| 1354 | * @param array $regularGroupIDs |
| 1355 | * Parent Group IDs |
| 1356 | * |
| 1357 | * @return array |
| 1358 | */ |
| 1359 | public static function getChildGroupIds($regularGroupIDs) { |
| 1360 | $childGroupIDs = []; |
| 1361 | |
| 1362 | foreach ((array) $regularGroupIDs as $regularGroupID) { |
| 1363 | // temporary store the child group ID(s) of regular group identified by $id, |
| 1364 | // later merge with main child group array |
| 1365 | $tempChildGroupIDs = []; |
| 1366 | // check that the regular group has any child group, if not then continue |
| 1367 | if ($childrenFound = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) { |
| 1368 | $tempChildGroupIDs[] = $childrenFound; |
| 1369 | } |
| 1370 | else { |
| 1371 | continue; |
| 1372 | } |
| 1373 | // as civicrm_group.children stores multiple group IDs in comma imploded string format, |
| 1374 | // so we need to convert it into array of child group IDs first |
| 1375 | $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs)); |
| 1376 | $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs); |
| 1377 | // recursively fetch the child group IDs |
| 1378 | while (count($tempChildGroupIDs)) { |
| 1379 | $tempChildGroupIDs = self::getChildGroupIds($tempChildGroupIDs); |
| 1380 | if (count($tempChildGroupIDs)) { |
| 1381 | $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs); |
| 1382 | } |
| 1383 | } |
| 1384 | } |
| 1385 | |
| 1386 | return $childGroupIDs; |
| 1387 | } |
| 1388 | |
| 1389 | /** |
| 1390 | * Check parent groups and filter out the disabled ones. |
| 1391 | * |
| 1392 | * @param array $parentArray |
| 1393 | * Array of group Ids. |
| 1394 | * |
| 1395 | * @return int |
| 1396 | */ |
| 1397 | public static function filterActiveGroups($parentArray) { |
| 1398 | if (count($parentArray) > 1) { |
| 1399 | $result = civicrm_api3('Group', 'get', [ |
| 1400 | 'id' => ['IN' => $parentArray], |
| 1401 | 'is_active' => TRUE, |
| 1402 | 'return' => 'id', |
| 1403 | ]); |
| 1404 | $activeParentGroupIDs = CRM_Utils_Array::collect('id', $result['values']); |
| 1405 | foreach ($parentArray as $key => $groupID) { |
| 1406 | if (!array_key_exists($groupID, $activeParentGroupIDs)) { |
| 1407 | unset($parentArray[$key]); |
| 1408 | } |
| 1409 | } |
| 1410 | } |
| 1411 | |
| 1412 | return reset($parentArray); |
| 1413 | } |
| 1414 | |
| 1415 | } |