3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Business object for managing custom data groups.
21 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
24 * Takes an associative array and creates a custom group object.
26 * This function is invoked from within the web form layer and also from the api layer
28 * @param array $params
29 * (reference) an assoc array of name/value pairs.
31 * @return CRM_Core_DAO_CustomGroup
34 public static function create(&$params) {
35 // create custom group dao, populate fields and then save.
36 $group = new CRM_Core_DAO_CustomGroup();
37 if (isset($params['title'])) {
38 $group->title
= $params['title'];
41 $extendsChildType = NULL;
42 // lets allow user to pass direct child type value, CRM-6893
43 if (!empty($params['extends_entity_column_value'])) {
44 $extendsChildType = $params['extends_entity_column_value'];
46 if (!CRM_Utils_System
::isNull($extendsChildType)) {
47 $b = self
::getMungedEntity($params['extends'], $params['extends_entity_column_id'] ??
NULL);
48 $registeredSubTypes = self
::getSubTypes()[$b];
49 if (is_array($extendsChildType)) {
50 foreach ($extendsChildType as $childType) {
51 if (!array_key_exists($childType, $registeredSubTypes) && !in_array($childType, $registeredSubTypes, TRUE)) {
52 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
57 if (!array_key_exists($extendsChildType, $registeredSubTypes) && !in_array($extendsChildType, $registeredSubTypes, TRUE)) {
58 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
60 $extendsChildType = [$extendsChildType];
62 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
63 if ($params['extends'] == 'Relationship') {
64 $extendsChildType = str_replace(['_a_b', '_b_a'], [
67 ], $extendsChildType);
69 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
70 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
71 CRM_Core_DAO
::VALUE_SEPARATOR
;
75 $extendsChildType = 'null';
77 $group->extends_entity_column_value
= $extendsChildType;
79 if (isset($params['id'])) {
80 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
85 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
89 'collapse_adv_display',
95 'extends_entity_column_id',
98 $current_db_version = CRM_Core_BAO_Domain
::version();
99 $is_public_version = version_compare($current_db_version, '4.7.19', '>=');
100 if ($is_public_version) {
101 $fields[] = 'is_public';
103 foreach ($fields as $field) {
104 if (isset($params[$field])) {
105 $group->$field = $params[$field];
108 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
109 $params['max_multiple'] >= '0'
110 ) ?
$params['max_multiple'] : 'null' : 'null';
112 $tableName = $tableNameNeedingIndexUpdate = NULL;
113 if (isset($params['id'])) {
114 $group->id
= $params['id'];
116 if (isset($params['is_multiple'])) {
117 // check whether custom group was changed from single-valued to multiple-valued
118 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
123 // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
124 $paramsIsMultiple = empty($params['is_multiple']) ?
0 : 1;
125 if ($paramsIsMultiple != $isMultiple) {
126 $tableNameNeedingIndexUpdate = CRM_Core_DAO
::getFieldValue(
127 'CRM_Core_DAO_CustomGroup',
135 $group->created_id
= $params['created_id'] ??
NULL;
136 $group->created_date
= $params['created_date'] ??
NULL;
138 // Process name only during create, so it never changes
139 if (!empty($params['name'])) {
140 $group->name
= CRM_Utils_String
::munge($params['name']);
143 $group->name
= CRM_Utils_String
::munge($group->title
);
146 self
::validateCustomGroupName($group);
148 if (isset($params['table_name'])) {
149 $tableName = $params['table_name'];
151 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
152 // Bad idea. Prevent group creation because it might lead to a broken configuration.
153 throw new CRM_Core_Exception(ts('Cannot create custom table because %1 is already a core table.', ['1' => $tableName]));
158 if (array_key_exists('is_reserved', $params)) {
159 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
161 $op = isset($params['id']) ?
'edit' : 'create';
162 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
164 // enclose the below in a transaction
165 $transaction = new CRM_Core_Transaction();
168 if (!isset($params['id'])) {
169 if (!isset($params['table_name'])) {
170 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 13));
171 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
173 $group->table_name
= $tableName;
174 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
180 // now create the table associated with this group
181 self
::createTable($group);
183 elseif ($tableNameNeedingIndexUpdate) {
184 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array
::value('is_multiple', $params));
187 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
188 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
192 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends']));
194 $transaction->commit();
197 CRM_Utils_System
::flushCache();
200 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
203 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
210 * Retrieve DB object and copy to defaults array.
212 * @param array $params
213 * Array of criteria values.
214 * @param array $defaults
215 * Array to be populated with found values.
218 * The DAO object, if found.
222 public static function retrieve($params, &$defaults) {
223 return self
::commonRetrieve(self
::class, $params, $defaults);
227 * Ensure group name does not conflict with an existing field
229 * @param CRM_Core_DAO_CustomGroup $group
231 public static function validateCustomGroupName(CRM_Core_DAO_CustomGroup
$group) {
232 $extends = in_array($group->extends, CRM_Contact_BAO_ContactType
::basicTypes(TRUE)) ?
'Contact' : $group->extends;
233 $extendsDAO = CRM_Core_DAO_AllCoreTables
::getFullName($extends);
235 $fields = array_column($extendsDAO::fields(), 'name');
236 if (in_array($group->name
, $fields)) {
243 * Update the is_active flag in the db.
246 * Id of the database record.
247 * @param bool $is_active
248 * Value we want to set the is_active field.
251 * true if we found and updated the object, else false
253 public static function setIsActive($id, $is_active) {
255 Civi
::cache('fields')->flush();
256 // reset ACL and system caches.
257 CRM_Core_BAO_Cache
::resetCaches();
260 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
263 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
267 * Determine if given entity (sub)type has any custom groups
269 * @param string $extends
270 * E.g. "Individual", "Activity".
271 * @param int $columnId
272 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
273 * @param string $columnValue
274 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
278 public static function hasCustomGroup($extends, $columnId, $columnValue) {
279 $dao = new CRM_Core_DAO_CustomGroup();
280 $dao->extends = $extends;
281 $dao->extends_entity_column_id
= $columnId;
282 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
283 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
284 //$dao->extends_entity_column_value = $columnValue;
285 return (bool) $dao->find();
289 * Determine if there are any CustomGroups for the given $activityTypeId.
290 * If none found, create one.
292 * @param int $activityTypeId
295 * TRUE if a group is found or created; FALSE on error
297 public static function autoCreateByActivityType($activityTypeId) {
298 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
302 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
305 'extends' => 'Activity',
306 'extends_entity_column_id' => NULL,
307 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded([$activityTypeId]),
308 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
312 $result = civicrm_api('CustomGroup', 'create', $params);
313 return !$result['is_error'];
317 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
318 * This may also include entity specific data values.
320 * An array containing all custom groups and their custom fields is returned.
322 * @param string $entityType
323 * Of the contact whose contact type is needed.
324 * @param array $toReturn
325 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
326 * @param int $entityID
327 * @param int $groupID
328 * @param array $subTypes
329 * @param string $subName
330 * @param bool $fromCache
331 * @param bool $onlySubType
332 * Only return specified subtype or return specified subtype + unrestricted fields.
333 * @param bool $returnAll
334 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
335 * api - through which it is properly tested - so can be refactored with some comfort.)
336 * @param bool|int $checkPermission
337 * Either a CRM_Core_Permission constant or FALSE to disable checks
338 * @param string|int $singleRecord
339 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
340 * @param bool $showPublicOnly
343 * Custom field 'tree'.
345 * The returned array is keyed by group id and has the custom group table fields
346 * and a subkey 'fields' holding the specific custom fields.
347 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
348 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
350 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
351 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
352 * With caching the performance impact would be small & the function would be cleaner
354 * @throws \CRM_Core_Exception
356 public static function getTree(
366 $checkPermission = CRM_Core_Permission
::EDIT
,
367 $singleRecord = NULL,
368 $showPublicOnly = FALSE
370 if ($checkPermission === TRUE) {
371 CRM_Core_Error
::deprecatedWarning('Unexpected TRUE passed to CustomGroup::getTree $checkPermission param.');
372 $checkPermission = CRM_Core_Permission
::EDIT
;
375 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
377 if (!is_array($subTypes)) {
378 if (empty($subTypes)) {
382 if (stristr($subTypes, ',')) {
383 $subTypes = explode(',', $subTypes);
386 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
393 // legacy hardcoded list of data to return
427 'extends_entity_column_id',
428 'extends_entity_column_value',
432 $current_db_version = CRM_Core_BAO_Domain
::version();
433 $is_public_version = version_compare($current_db_version, '4.7.19', '>=');
434 $serialize_version = version_compare($current_db_version, '5.27.alpha1', '>=');
435 if ($is_public_version) {
436 $tableData['custom_group'][] = 'is_public';
438 if ($serialize_version) {
439 $tableData['custom_field'][] = 'serialize';
441 if (!$toReturn ||
!is_array($toReturn)) {
442 $toReturn = $tableData;
445 // Supply defaults and remove unknown array keys
446 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
447 // Merge in required fields that we must have
448 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
449 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
450 // Validate return fields
451 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
452 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
457 foreach ($toReturn as $tableName => $tableColumn) {
458 foreach ($tableColumn as $columnName) {
459 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
462 $strSelect = "SELECT " . implode(', ', $select);
464 // from, where, order by
466 FROM civicrm_custom_group
467 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
470 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
471 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
472 $entityType == 'Household'
474 $in = "'$entityType', 'Contact'";
476 elseif (strpos($entityType, "'") !== FALSE) {
477 // this allows the calling function to send in multiple entity types
482 $in = "'$entityType'";
488 if (!empty($subTypes)) {
489 foreach ($subTypes as $key => $subType) {
490 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
492 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
494 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
498 WHERE civicrm_custom_group.is_active = 1
499 AND civicrm_custom_field.is_active = 1
500 AND civicrm_custom_group.extends IN ($in)
504 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
505 $params[$sqlParamKey] = [$subName, 'String'];
506 $sqlParamKey = $sqlParamKey +
1;
511 WHERE civicrm_custom_group.is_active = 1
512 AND civicrm_custom_field.is_active = 1
513 AND civicrm_custom_group.extends IN ($in)
516 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
521 // since we want a specific group id we add it to the where clause
522 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
523 $params[$sqlParamKey] = [$groupID, 'Integer'];
526 // since groupID is false we need to show all Inline groups
527 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
529 if ($checkPermission) {
530 // ensure that the user has access to these custom groups
531 $strWhere .= " AND " .
532 CRM_Core_Permission
::customGroupClause($checkPermission,
533 'civicrm_custom_group.'
537 if ($showPublicOnly && $is_public_version) {
538 $strWhere .= "AND civicrm_custom_group.is_public = 1";
542 ORDER BY civicrm_custom_group.weight,
543 civicrm_custom_group.title,
544 civicrm_custom_field.weight,
545 civicrm_custom_field.label
548 // final query string
549 $queryString = "$strSelect $strFrom $strWhere $orderBy";
551 // lets see if we can retrieve the groupTree from cache
552 $cacheString = $queryString;
554 $cacheString .= "_{$groupID}";
557 $cacheString .= "_Inline";
560 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
561 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
562 $cache = CRM_Utils_Cache
::singleton();
564 $groupTree = $cache->get($cacheKey);
565 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
568 if (empty($groupTree)) {
569 list($multipleFieldGroups, $groupTree) = self
::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType);
571 $cache->set($cacheKey, $groupTree);
572 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
574 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
575 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
576 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
577 $singleFieldTables = [];
578 // now that we have all the groups and fields, lets get the values
579 // since we need to know the table and field names
580 // add info to groupTree
582 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
583 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
585 $select = $from = $where = [];
586 $groupTree['info']['where'] = NULL;
588 foreach ($groupTree['info']['tables'] as $table => $fields) {
589 $groupTree['info']['from'][] = $table;
591 "{$table}.id as {$table}_id",
592 "{$table}.entity_id as {$table}_entity_id",
594 foreach ($fields as $column => $dontCare) {
595 $select[] = "{$table}.{$column} as {$table}_{$column}";
597 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
599 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
600 if (in_array($table, $multipleFieldGroups) &&
601 self
::customGroupDataExistsForEntity($entityID, $table)
603 $entityMultipleSelectClauses[$table] = $select;
606 $singleFieldTables[] = $table;
607 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
612 if ($entityID && !empty($singleFieldTables)) {
613 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
615 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
616 if (!empty($multipleFieldTablesWithEntityData)) {
617 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
625 * Clean and validate the filter before it is used in a db query.
627 * @param string $entityType
628 * @param string $subType
631 * @throws \CRM_Core_Exception
633 protected static function validateSubTypeByEntity($entityType, $subType) {
634 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
635 if (is_numeric($subType)) {
639 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
640 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
642 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
643 throw new CRM_Core_Exception('Invalid Entity Filter');
645 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
646 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
647 if (!array_key_exists($subType, $subTypes)) {
648 throw new CRM_Core_Exception('Invalid Filter');
654 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
655 * a WHERE condition for rows that include $value. Use whereListHas().
657 * @param string $column
658 * @param string $value
659 * @param string $delimiter
663 private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
665 $bareValue = trim($value, $delimiter);
666 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
667 return "($column LIKE \"$escapedValue\")";
671 * Check whether the custom group has any data for the given entity.
673 * @param int $entityID
674 * Id of entity for whom we are checking data for.
675 * @param string $table
676 * Table that we are checking.
678 * @param bool $getCount
681 * does this entity have data in this custom table
683 public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
687 WHERE entity_id = $entityID
689 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
691 return $recordExists;
693 return (bool) $recordExists;
697 * Build the group tree for Custom fields which are not 'is_multiple'
699 * The combination of all these fields in one query with a 'using' join was not working for
700 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
701 * mechanism as it seemed to be acceptable in this context
703 * @param array $groupTree
704 * (reference) group tree array which is being built.
705 * @param int $entityID
706 * Id of entity for whom the tree is being build up.
707 * @param array $entitySingleSelectClauses
708 * Array of select clauses relevant to the entity.
709 * @param array $singleFieldTablesWithEntityData
710 * Array of tables in which this entity has data.
712 public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
713 $select = implode(', ', $entitySingleSelectClauses);
714 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
715 foreach ($singleFieldTablesWithEntityData as $table) {
716 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
722 WHERE first.entity_id = $entityID
724 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
728 * Build the group tree for Custom fields which are 'is_multiple'
730 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
732 * @param array $groupTree
733 * (reference) group tree array which is being built.
734 * @param int $entityID
735 * Id of entity for whom the tree is being build up.
736 * @param array $entityMultipleSelectClauses
737 * Array of select clauses relevant to the entity.
738 * @param array $multipleFieldTablesWithEntityData
739 * Array of tables in which this entity has data.
740 * @param string|int $singleRecord
741 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
743 public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
744 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
745 $select = implode(',', $selectClauses);
749 WHERE entity_id = $entityID
752 $offset = $singleRecord - 1;
753 $query .= " LIMIT {$offset}, 1";
755 self
::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
760 * Build the tree entity data - starting from a query retrieving the custom fields build the group
761 * tree data for the relevant entity (entity is included in the query).
763 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
765 * @param array $groupTree
766 * (reference) group tree array which is being built.
767 * @param string $query
768 * @param array $includedTables
769 * Tables to include - required because the function (for historical reasons).
770 * iterates through the group tree
771 * @param string|int $singleRecord
772 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
774 public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
775 $dao = CRM_Core_DAO
::executeQuery($query);
776 while ($dao->fetch()) {
777 foreach ($groupTree as $groupID => $group) {
778 if ($groupID === 'info') {
781 $table = $groupTree[$groupID]['table_name'];
782 //working from the groupTree instead of the table list means we have to iterate & exclude.
783 // this could possibly be re-written as other parts of the function have been refactored
784 // for now we just check if the given table is to be included in this function
785 if (!in_array($table, $includedTables)) {
788 foreach ($group['fields'] as $fieldID => $dontCare) {
789 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
796 * Build the entity-specific custom data into the group tree on a per-field basis
799 * Object representing the custom field to be populated into the groupTree.
800 * @param array $groupTree
801 * (reference) the group tree being build.
802 * @param string $table
804 * @param int $groupID
806 * @param int $fieldID
808 * @param string|int $singleRecord
809 * holds 'new' or id if loading view/edit/copy for a single record.
811 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
812 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
813 $idName = "{$table}_id";
814 $fieldName = "{$table}_{$column}";
815 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
816 if ($dataType == 'File') {
817 if (isset($dao->$fieldName)) {
818 $config = CRM_Core_Config
::singleton();
819 $fileDAO = new CRM_Core_DAO_File();
820 $fileDAO->id
= $dao->$fieldName;
822 if ($fileDAO->find(TRUE)) {
823 $entityIDName = "{$table}_entity_id";
824 $fileHash = CRM_Core_BAO_File
::generateFileHash($dao->$entityIDName, $fileDAO->id
);
825 $customValue['id'] = $dao->$idName;
826 $customValue['data'] = $fileDAO->uri
;
827 $customValue['fid'] = $fileDAO->id
;
828 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
829 $customValue['displayURL'] = NULL;
830 $deleteExtra = ts('Are you sure you want to delete attached file.');
832 CRM_Core_Action
::DELETE
=> [
833 'name' => ts('Delete Attached File'),
834 'url' => 'civicrm/file',
835 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
836 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
837 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
840 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
841 CRM_Core_Action
::DELETE
,
843 'id' => $fileDAO->id
,
844 'eid' => $dao->$entityIDName,
850 'file.manage.delete',
854 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
855 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
856 if ($fileDAO->mime_type
== "image/jpeg" ||
857 $fileDAO->mime_type
== "image/pjpeg" ||
858 $fileDAO->mime_type
== "image/gif" ||
859 $fileDAO->mime_type
== "image/x-png" ||
860 $fileDAO->mime_type
== "image/png"
862 $customValue['displayURL'] = $customValue['fileURL'];
863 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
868 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
870 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId);
871 if ($path && file_exists($path)) {
872 list($imageWidth, $imageHeight) = getimagesize($path);
873 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
874 $customValue['imageThumbWidth'] = $imageThumbWidth;
875 $customValue['imageThumbHeight'] = $imageThumbHeight;
882 'id' => $dao->$idName,
889 'id' => $dao->$idName,
890 'data' => $dao->$fieldName,
894 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
895 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
897 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
898 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
900 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
901 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
904 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
909 * Get the group title.
917 public static function getTitle($id) {
918 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
922 * Get custom group details for a group.
924 * An array containing custom group details (including their custom field) is returned.
926 * @param int $groupId
927 * Group id whose details are needed.
928 * @param bool $searchable
929 * Is this field searchable.
930 * @param array $extends
931 * Which table does it extend if any.
933 * @param bool $inSelector
936 * array consisting of all group and field details
938 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
942 // using tableData to build the queryString
944 'civicrm_custom_field' => [
968 'civicrm_custom_group' => [
975 'collapse_adv_display',
977 'extends_entity_column_value',
985 foreach ($tableData as $tableName => $tableColumn) {
986 foreach ($tableColumn as $columnName) {
987 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
990 $select = 'SELECT ' . implode(', ', $s);
992 // from, where, order by
993 $from = " FROM civicrm_custom_field, civicrm_custom_group";
994 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
995 AND civicrm_custom_group.is_active = 1
996 AND civicrm_custom_field.is_active = 1 ";
998 $params[1] = [$groupId, 'Integer'];
999 $where .= " AND civicrm_custom_group.id = %1";
1003 $where .= " AND civicrm_custom_field.is_searchable = 1";
1007 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1012 foreach ($extends as $e) {
1013 $clause[] = "civicrm_custom_group.extends = '$e'";
1015 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1017 //include case activities customdata if case is enabled
1018 if (in_array('Activity', $extends)) {
1019 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1020 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1021 $params[2] = [CRM_Core_DAO
::VALUE_SEPARATOR
, 'String'];
1025 // ensure that the user has access to these custom groups
1027 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1028 'civicrm_custom_group.'
1031 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1033 // final query string
1034 $queryString = $select . $from . $where . $orderBy;
1037 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1040 while ($crmDAO->fetch()) {
1041 $groupId = $crmDAO->civicrm_custom_group_id
;
1042 $fieldId = $crmDAO->civicrm_custom_field_id
;
1044 // create an array for groups if it does not exist
1045 if (!array_key_exists($groupId, $groupTree)) {
1046 $groupTree[$groupId] = [];
1047 $groupTree[$groupId]['id'] = $groupId;
1049 foreach ($tableData['civicrm_custom_group'] as $v) {
1050 $fullField = "civicrm_custom_group_" . $v;
1052 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1056 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1059 $groupTree[$groupId]['fields'] = [];
1062 // add the fields now (note - the query row will always contain a field)
1063 $groupTree[$groupId]['fields'][$fieldId] = [];
1064 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1066 foreach ($tableData['civicrm_custom_field'] as $v) {
1067 $fullField = "civicrm_custom_field_" . $v;
1068 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1071 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1079 * @param $entityType
1081 * @param string $cidToken
1085 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1087 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1089 // get 'Tab' and 'Tab with table' groups
1090 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1091 $customGroupDAO->whereAdd("is_active = 1");
1093 // add whereAdd for entity type
1094 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1098 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1099 $customGroupDAO->whereAdd($permissionClause);
1102 $customGroupDAO->orderBy('weight');
1103 $customGroupDAO->find();
1105 // process each group with menu tab
1106 while ($customGroupDAO->fetch()) {
1108 $group['id'] = $customGroupDAO->id
;
1109 $group['path'] = $path;
1110 $group['title'] = "$customGroupDAO->title";
1111 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1112 $group['extra'] = ['gid' => $customGroupDAO->id
];
1113 $group['table_name'] = $customGroupDAO->table_name
;
1114 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1115 $group['icon'] = $customGroupDAO->icon
;
1123 * Get the table name for the entity type
1124 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1125 * tableName is 'civicrm_contact'
1127 * @param string $entityType
1128 * What entity are we extending here ?.
1133 * @see _apachesolr_civiAttachments_dereference_file_parent
1135 public static function getTableNameByEntityName($entityType) {
1136 switch ($entityType) {
1140 case 'Organization':
1141 return 'civicrm_contact';
1144 return CRM_Core_DAO_AllCoreTables
::getTableForEntityName($entityType);
1149 * Get a list of custom groups which extend a given entity type.
1150 * If there are custom-groups which only apply to certain subtypes,
1151 * those WILL be included.
1153 * @param string $entityType
1155 * @return CRM_Core_DAO_CustomGroup
1157 public static function getAllCustomGroupsByBaseEntity($entityType) {
1158 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1159 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1160 return $customGroupDAO;
1164 * Add the whereAdd clause for the DAO depending on the type of entity
1165 * the custom group is extending.
1167 * @param object $customGroupDAO
1168 * @param string $entityType
1169 * What entity are we extending here ?.
1171 * @param int $entityID
1172 * @param bool $allSubtypes
1174 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1175 $addSubtypeClause = FALSE;
1176 // This function isn't really accessible with user data but since the string
1177 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1179 $entityType = CRM_Core_DAO
::escapeString($entityType);
1181 switch ($entityType) {
1183 // if contact, get all related to contact
1184 $extendList = "'Contact','Individual','Household','Organization'";
1185 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1186 if (!$allSubtypes) {
1187 $addSubtypeClause = TRUE;
1193 case 'Organization':
1194 // is I/H/O then get I/H/O and contact
1195 $extendList = "'Contact','$entityType'";
1196 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1197 if (!$allSubtypes) {
1198 $addSubtypeClause = TRUE;
1203 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1207 if ($addSubtypeClause) {
1208 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1210 if (!empty($csType)) {
1211 $subtypeClause = [];
1212 foreach ($csType as $subtype) {
1213 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1214 CRM_Core_DAO
::VALUE_SEPARATOR
;
1215 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1217 $subtypeClause[] = "extends_entity_column_value IS NULL";
1218 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1222 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1228 * Delete the Custom Group.
1230 * @param CRM_Core_BAO_CustomGroup $group
1231 * Custom group object.
1232 * @param bool $force
1233 * whether to force the deletion, even if there are custom fields.
1236 * False if field exists for this group, true if group gets deleted.
1238 public static function deleteGroup($group, $force = FALSE) {
1240 //check whether this contain any custom fields
1241 $customField = new CRM_Core_DAO_CustomField();
1242 $customField->custom_group_id
= $group->id
;
1243 $customField->find();
1245 // return early if there are custom fields and we're not
1246 // forcing the delete, otherwise delete the fields one by one
1247 while ($customField->fetch()) {
1251 CRM_Core_BAO_CustomField
::deleteField($customField);
1254 // drop the table associated with this custom group
1255 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1257 //delete custom group
1260 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1266 * Delete a record from supplied params.
1267 * API3 calls deleteGroup() which removes the related civicrm_value_X table.
1268 * This function does the same for API4.
1270 * @param array $record
1272 * @return CRM_Core_DAO
1273 * @throws CRM_Core_Exception
1275 public static function deleteRecord(array $record) {
1276 $table = CRM_Core_DAO
::getFieldValue(__CLASS__
, $record['id'], 'table_name');
1277 $result = parent
::deleteRecord($record);
1278 CRM_Core_BAO_SchemaHandler
::dropTable($table);
1285 * @param array $groupTree
1286 * @param array $defaults
1287 * @param bool $viewMode
1288 * @param bool $inactiveNeeded
1289 * @param int $action
1291 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1292 foreach ($groupTree as $id => $group) {
1293 if (!isset($group['fields'])) {
1296 foreach ($group['fields'] as $field) {
1297 if (isset($field['element_value'])) {
1298 $value = $field['element_value'];
1300 elseif (isset($field['default_value']) &&
1301 ($action != CRM_Core_Action
::UPDATE ||
1303 !array_key_exists('element_value', $field)
1306 $value = $viewMode ?
NULL : $field['default_value'];
1312 if (empty($field['element_name'])) {
1316 $elementName = $field['element_name'];
1317 $serialize = CRM_Core_BAO_CustomField
::isSerialized($field);
1320 if ($field['data_type'] != 'Country' && $field['data_type'] != 'StateProvince' && $field['data_type'] != 'ContactReference') {
1321 $defaults[$elementName] = [];
1322 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1324 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1325 if (isset($value)) {
1326 foreach ($customOption as $customValue => $customLabel) {
1327 if (in_array($customValue, $checkedData)) {
1328 if ($field['html_type'] == 'CheckBox') {
1329 $defaults[$elementName][$customValue] = 1;
1332 $defaults[$elementName][$customValue] = $customValue;
1336 $defaults[$elementName][$customValue] = 0;
1342 if (isset($field['customValue']['data'])) {
1343 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1344 foreach ($customOption as $val) {
1345 if (in_array($val['value'], $checkedData)) {
1346 if ($field['html_type'] == 'CheckBox') {
1347 $defaults[$elementName][$val['value']] = 1;
1350 $defaults[$elementName][$val['value']] = $val['value'];
1354 $defaults[$elementName][$val['value']] = 0;
1359 // Values may be "array strings" or actual arrays. Handle both.
1360 if (is_array($value) && count($value)) {
1361 CRM_Utils_Array
::formatArrayKeys($value);
1362 $checkedValue = $value;
1365 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1367 foreach ($customOption as $val) {
1368 if (in_array($val['value'], $checkedValue)) {
1369 if ($field['html_type'] == 'CheckBox') {
1370 $defaults[$elementName][$val['value']] = 1;
1373 $defaults[$elementName][$val['value']] = $val['value'];
1381 if (isset($value)) {
1382 // Values may be "array strings" or actual arrays. Handle both.
1383 if (is_array($value) && count($value)) {
1384 CRM_Utils_Array
::formatArrayKeys($value);
1385 $checkedValue = $value;
1387 // Serialized values from db
1388 elseif ($value === '' ||
strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1389 $checkedValue = CRM_Utils_Array
::explodePadded($value);
1391 // Comma-separated values e.g. from a select2 widget during reload on form error
1393 $checkedValue = explode(',', $value);
1395 foreach ($checkedValue as $val) {
1397 $defaults[$elementName][$val] = $val;
1404 if ($field['data_type'] == 'Country') {
1406 $defaults[$elementName] = $value;
1409 $config = CRM_Core_Config
::singleton();
1410 $defaults[$elementName] = $config->defaultContactCountry
;
1414 if ($field['data_type'] == "Float") {
1415 $defaults[$elementName] = (float) $value;
1417 elseif ($field['data_type'] == 'Money' &&
1418 $field['html_type'] == 'Text'
1420 $defaults[$elementName] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($value);
1423 $defaults[$elementName] = $value;
1432 * Old function only called from one place...
1433 * @see CRM_Dedupe_Finder::formatParams
1435 * @param array $groupTree
1436 * @param array $params
1437 * @param bool $skipFile
1439 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1440 // Get the Custom form values and groupTree
1441 foreach ($groupTree as $groupID => $group) {
1442 if ($groupID === 'info') {
1445 foreach ($group['fields'] as $field) {
1446 $fieldId = $field['id'];
1447 $serialize = CRM_Core_BAO_CustomField
::isSerialized($field);
1449 // Reset all checkbox, radio and multiselect data
1450 if ($field['html_type'] == 'Radio' ||
$serialize) {
1451 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1455 foreach ($params as $key => $val) {
1456 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1457 $match[1] == $field['id']
1463 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1464 // field exists in db so populate value from "form".
1465 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
1468 // Serialize checkbox and multi-select data (using array keys for checkbox)
1470 $v = ($v && $field['html_type'] === 'Checkbox') ?
array_keys($v) : $v;
1471 $v = $v ? CRM_Utils_Array
::implodePadded($v) : NULL;
1474 switch ($field['html_type']) {
1477 $date = CRM_Utils_Date
::processDate($v);
1478 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1486 // store the file in d/b
1487 $entityId = explode('=', $groupTree['info']['where'][0]);
1488 $fileParams = ['upload_date' => date('YmdHis')];
1490 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1491 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1494 $fileParams['uri'] = $v['name'];
1495 $fileParams['mime_type'] = $v['type'];
1496 CRM_Core_BAO_File
::filePostProcess($v['name'],
1497 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1498 $groupTree[$groupID]['table_name'],
1503 'custom_' . $fieldId,
1509 'entity_table' => $groupTree[$groupID]['table_name'],
1510 'entity_id' => $entityId[1],
1513 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1518 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1522 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1530 * Generic function to build all the form elements for a specific group tree.
1532 * @param CRM_Core_Form $form
1534 * @param array $groupTree
1535 * The group tree object.
1536 * @param bool $inactiveNeeded
1537 * Return inactive custom groups.
1538 * @param string $prefix
1539 * Prefix for custom grouptree assigned to template.
1541 * @throws \CiviCRM_API3_Exception
1543 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1544 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1546 foreach ($groupTree as $id => $group) {
1547 foreach ($group['fields'] as $field) {
1548 $required = $field['is_required'] ??
NULL;
1550 if ($field['data_type'] == 'File') {
1551 if (!empty($field['element_value']['data'])) {
1556 $fieldId = $field['id'];
1557 $elementName = $field['element_name'];
1558 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1559 if ($form->getAction() == CRM_Core_Action
::VIEW
) {
1560 $form->getElement($elementName)->freeze();
1567 * Extract the get params from the url, validate and store it in session.
1569 * @param CRM_Core_Form $form
1571 * @param string $type
1572 * The type of custom group we are using.
1575 * @throws \CRM_Core_Exception
1576 * @throws \CiviCRM_API3_Exception
1578 public static function extractGetParams(&$form, $type) {
1583 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1592 foreach ($groupTree as $group) {
1593 if (!isset($group['fields'])) {
1596 foreach ($group['fields'] as $key => $field) {
1597 $fieldName = 'custom_' . $key;
1598 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1602 if (!in_array($field['html_type'], $htmlType) ||
1603 $field['data_type'] == 'Boolean'
1605 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1607 if (CRM_Core_BAO_CustomField
::isSerialized($field)) {
1608 $value = str_replace("|", ",", $value);
1609 $mulValues = explode(',', $value);
1610 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1612 foreach ($mulValues as $v1) {
1613 foreach ($customOption as $coID => $coValue) {
1614 if (strtolower(trim($coValue['label'])) ==
1615 strtolower(trim($v1))
1617 $val[$coValue['value']] = 1;
1629 elseif ($field['html_type'] === 'Select' ||
1630 ($field['html_type'] === 'Radio' &&
1631 $field['data_type'] !== 'Boolean'
1634 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1635 foreach ($customOption as $customID => $coValue) {
1636 if (strtolower(trim($coValue['label'])) ==
1637 strtolower(trim($value))
1639 $value = $coValue['value'];
1644 elseif ($field['data_type'] === 'Date') {
1645 $valid = CRM_Utils_Rule
::date($value);
1649 $customValue[$fieldName] = $value;
1655 return $customValue;
1659 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1660 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1662 * @param int $customFieldId
1664 * @param array $removeCustomFieldTypes
1665 * Remove custom fields of a type eg: array("Individual") ;.
1668 * false if it matches else true
1670 * @throws \CRM_Core_Exception
1672 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1673 $query = 'SELECT cg.extends as extends
1674 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1675 WHERE cg.id = cf.custom_group_id
1677 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1679 $extends = CRM_Core_DAO
::singleValueQuery($query);
1681 if (in_array($extends, $removeCustomFieldTypes)) {
1693 public static function mapTableName($table) {
1698 case 'Organization':
1699 return 'civicrm_contact';
1702 return 'civicrm_activity';
1705 return 'civicrm_group';
1707 case 'Contribution':
1708 return 'civicrm_contribution';
1710 case 'ContributionRecur':
1711 return 'civicrm_contribution_recur';
1713 case 'Relationship':
1714 return 'civicrm_relationship';
1717 return 'civicrm_event';
1720 return 'civicrm_membership';
1723 case 'ParticipantRole':
1724 case 'ParticipantEventName':
1725 case 'ParticipantEventType':
1726 return 'civicrm_participant';
1729 return 'civicrm_grant';
1732 return 'civicrm_pledge';
1735 return 'civicrm_address';
1738 return 'civicrm_campaign';
1742 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1743 $qParams = [1 => [$table, 'String']];
1744 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1747 return 'civicrm_contact';
1750 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1751 if (array_key_exists($table, $extendObjs)) {
1752 return $extendObjs[$table];
1754 throw new CRM_Core_Exception('Unknown error');
1762 * @throws \Exception
1764 public static function createTable($group) {
1766 'name' => $group->table_name
,
1767 'is_multiple' => $group->is_multiple ?
1 : 0,
1768 'extends_name' => self
::mapTableName($group->extends),
1771 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1773 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1777 * Function returns formatted groupTree, so that form can be easily built in template
1779 * @param array $groupTree
1780 * @param int $groupCount
1781 * Group count by default 1, but can vary for multiple value custom data.
1782 * @param \CRM_Core_Form $form
1785 * @throws \CRM_Core_Exception
1787 public static function formatGroupTree($groupTree, $groupCount = 1, &$form = NULL) {
1788 $formattedGroupTree = [];
1789 $uploadNames = $formValues = [];
1791 // retrieve qf key from url
1792 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1794 // fetch submitted custom field values later use to set as a default values
1796 $submittedValues = Civi
::cache('customData')->get($qfKey);
1799 foreach ($groupTree as $key => $value) {
1800 if ($key === 'info') {
1804 // add group information
1805 $formattedGroupTree[$key]['name'] = $value['name'] ??
NULL;
1806 $formattedGroupTree[$key]['title'] = $value['title'] ??
NULL;
1807 $formattedGroupTree[$key]['help_pre'] = $value['help_pre'] ??
NULL;
1808 $formattedGroupTree[$key]['help_post'] = $value['help_post'] ??
NULL;
1809 $formattedGroupTree[$key]['collapse_display'] = $value['collapse_display'] ??
NULL;
1810 $formattedGroupTree[$key]['collapse_adv_display'] = $value['collapse_adv_display'] ??
NULL;
1811 $formattedGroupTree[$key]['style'] = $value['style'] ??
NULL;
1813 // this params needed of building multiple values
1814 $formattedGroupTree[$key]['is_multiple'] = $value['is_multiple'] ??
NULL;
1815 $formattedGroupTree[$key]['extends'] = $value['extends'] ??
NULL;
1816 $formattedGroupTree[$key]['extends_entity_column_id'] = $value['extends_entity_column_id'] ??
NULL;
1817 $formattedGroupTree[$key]['extends_entity_column_value'] = $value['extends_entity_column_value'] ??
NULL;
1818 $formattedGroupTree[$key]['subtype'] = $value['subtype'] ??
NULL;
1819 $formattedGroupTree[$key]['max_multiple'] = $value['max_multiple'] ??
NULL;
1821 // Properties that might have been filtered out but which
1822 // should be present to avoid smarty e-notices.
1823 $expectedProperties = ['options_per_line', 'help_pre', 'help_post'];
1824 // add field information
1825 foreach ($value['fields'] as $k => $properties) {
1826 $properties = array_merge(array_fill_keys($expectedProperties, NULL), $properties);
1827 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1828 if (isset($properties['customValue']) &&
1829 !CRM_Utils_System
::isNull($properties['customValue']) &&
1830 !isset($properties['element_value'])
1832 if (isset($properties['customValue'][$groupCount])) {
1833 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1834 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1835 if ($properties['data_type'] === 'File') {
1836 $properties['element_value'] = $properties['customValue'][$groupCount];
1837 $uploadNames[] = $properties['element_name'];
1840 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1844 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1845 $formValues[$properties['element_name']] = $value;
1847 elseif (isset($submittedValues[$properties['element_name']])) {
1848 $properties['element_value'] = $submittedValues[$properties['element_name']];
1850 unset($properties['customValue']);
1851 $formattedGroupTree[$key]['fields'][$k] = $properties;
1856 if (count($formValues)) {
1857 $qf = $form->get('qfKey');
1858 $form->assign('qfKey', $qf);
1859 Civi
::cache('customData')->set($qf, $formValues);
1862 // hack for field type File
1863 $formUploadNames = $form->get('uploadNames');
1864 if (is_array($formUploadNames)) {
1865 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1868 $form->set('uploadNames', $uploadNames);
1871 return $formattedGroupTree;
1875 * Build custom data view.
1877 * @param CRM_Core_Form|CRM_Core_Page $form
1879 * @param array $groupTree
1880 * @param bool $returnCount
1881 * True if customValue count needs to be returned.
1883 * @param null $prefix
1884 * @param int $customValueId
1885 * @param int $entityId
1886 * @param bool $checkEditPermission
1889 * @throws \CRM_Core_Exception
1891 public static function buildCustomDataView(&$form, $groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL, $checkEditPermission = FALSE) {
1892 // Filter out pesky extra info
1893 unset($groupTree['info']);
1897 $editableGroups = [];
1898 if ($checkEditPermission) {
1899 $editableGroups = \CRM_Core_Permission
::customGroup(CRM_Core_Permission
::EDIT
);
1902 foreach ($groupTree as $key => $group) {
1904 foreach ($group['fields'] as $k => $properties) {
1905 $groupID = $group['id'];
1906 if (!empty($properties['customValue'])) {
1907 foreach ($properties['customValue'] as $values) {
1908 if (!empty($customValueId) && $customValueId != $values['id']) {
1911 $details[$groupID][$values['id']]['title'] = $group['title'] ??
NULL;
1912 $details[$groupID][$values['id']]['name'] = $group['name'] ??
NULL;
1913 $details[$groupID][$values['id']]['help_pre'] = $group['help_pre'] ??
NULL;
1914 $details[$groupID][$values['id']]['help_post'] = $group['help_post'] ??
NULL;
1915 $details[$groupID][$values['id']]['collapse_display'] = $group['collapse_display'] ??
NULL;
1916 $details[$groupID][$values['id']]['collapse_adv_display'] = $group['collapse_adv_display'] ??
NULL;
1917 $details[$groupID][$values['id']]['style'] = $group['style'] ??
NULL;
1918 $details[$groupID][$values['id']]['fields'][$k] = [
1919 'field_title' => $properties['label'] ??
NULL,
1920 'field_type' => $properties['html_type'] ??
NULL,
1921 'field_data_type' => $properties['data_type'] ??
NULL,
1922 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1923 'options_per_line' => $properties['options_per_line'] ??
NULL,
1924 'data' => $values['data'],
1926 // editable = whether this set contains any non-read-only fields
1927 if (!isset($details[$groupID][$values['id']]['editable'])) {
1928 $details[$groupID][$values['id']]['editable'] = FALSE;
1930 if (empty($properties['is_view']) && in_array($key, $editableGroups)) {
1931 $details[$groupID][$values['id']]['editable'] = TRUE;
1933 // also return contact reference contact id if user has view all or edit all contacts perm
1934 if ($details[$groupID][$values['id']]['fields'][$k]['field_data_type'] === 'ContactReference'
1935 && CRM_Core_Permission
::check([['view all contacts', 'edit all contacts']])
1937 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'] = [];
1938 $path = CRM_Contact_DAO_Contact
::getEntityPaths()['view'];
1939 foreach (CRM_Utils_Array
::explodePadded($values['data'] ??
[]) as $contactId) {
1940 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'display_name');
1942 $url = CRM_Utils_System
::url(str_replace('[id]', $contactId, $path));
1943 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'][] = '<a href="' . $url . '" title="' . htmlspecialchars(ts('View Contact')) . '">' .
1944 $displayName . '</a>';
1951 $details[$groupID][0]['title'] = $group['title'] ??
NULL;
1952 $details[$groupID][0]['name'] = $group['name'] ??
NULL;
1953 $details[$groupID][0]['help_pre'] = $group['help_pre'] ??
NULL;
1954 $details[$groupID][0]['help_post'] = $group['help_post'] ??
NULL;
1955 $details[$groupID][0]['collapse_display'] = $group['collapse_display'] ??
NULL;
1956 $details[$groupID][0]['collapse_adv_display'] = $group['collapse_adv_display'] ??
NULL;
1957 $details[$groupID][0]['style'] = $group['style'] ??
NULL;
1958 $details[$groupID][0]['fields'][$k] = ['field_title' => $properties['label'] ??
NULL];
1964 // return a single value count if group id is passed to function
1965 // else return a groupId and count mapped array
1967 return count($details[$gID]);
1971 foreach ($details as $key => $value) {
1972 $countValue[$key] = count($details[$key]);
1978 $form->addExpectedSmartyVariables([
1979 'multiRecordDisplay',
1983 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1989 * Get the custom group titles by custom field ids.
1991 * @param array $fieldIds
1992 * Array of custom field ids.
1994 * @return array|NULL
1995 * array consisting of groups and fields labels with ids.
1997 public static function getGroupTitles($fieldIds) {
1998 if (!is_array($fieldIds) && empty($fieldIds)) {
2003 $fIds = "(" . implode(',', $fieldIds) . ")";
2006 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2007 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2008 FROM civicrm_custom_group, civicrm_custom_field
2009 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2010 AND civicrm_custom_field.id IN {$fIds}";
2012 $dao = CRM_Core_DAO
::executeQuery($query);
2013 while ($dao->fetch()) {
2014 $groupLabels[$dao->fieldID
] = [
2015 'fieldID' => $dao->fieldID
,
2016 'fieldLabel' => $dao->fieldLabel
,
2017 'groupID' => $dao->groupID
,
2018 'groupTitle' => $dao->groupTitle
,
2022 return $groupLabels;
2025 public static function dropAllTables() {
2026 $query = "SELECT table_name FROM civicrm_custom_group";
2027 $dao = CRM_Core_DAO
::executeQuery($query);
2029 while ($dao->fetch()) {
2030 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2031 CRM_Core_DAO
::executeQuery($query);
2036 * Check whether custom group is empty or not.
2042 * true if empty otherwise false.
2044 public static function isGroupEmpty($gID) {
2049 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2054 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2055 $value = CRM_Core_DAO
::singleValueQuery($query);
2057 if (empty($value)) {
2065 * Get the list of types for objects that a custom group extends to.
2067 * @param array $types
2068 * Var which should have the list appended.
2072 * @throws \Exception
2074 public static function getExtendedObjectTypes(&$types = []) {
2075 static $flag = FALSE, $objTypes = [];
2079 CRM_Core_OptionValue
::getValues(['name' => 'cg_extend_objects'], $extendObjs, 'weight', TRUE);
2081 foreach ($extendObjs as $ovId => $ovValues) {
2082 if ($ovValues['description']) {
2083 // description is expected to be a callback func to subtypes
2084 list($callback, $args) = explode(';', trim($ovValues['description']));
2090 if (!is_array($args)) {
2091 throw new CRM_Core_Exception('Arg is not of type array');
2094 list($className) = explode('::', $callback);
2095 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
2097 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2103 $types = array_merge($types, $objTypes);
2108 * @param int $customGroupId
2109 * @param int $entityId
2113 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2114 // check whether the group is multiple
2115 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2116 $isMultiple = (bool) $isMultiple;
2117 $hasReachedMax = FALSE;
2119 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2121 if (!$maxMultiple) {
2122 $hasReachedMax = FALSE;
2125 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2126 // count the number of entries for a entity
2127 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2128 $params = [1 => [$entityId, 'Integer']];
2129 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2131 if ($count >= $maxMultiple) {
2132 $hasReachedMax = TRUE;
2136 return $hasReachedMax;
2142 public static function getMultipleFieldGroup() {
2143 $multipleGroup = [];
2144 $dao = new CRM_Core_DAO_CustomGroup();
2145 $dao->is_multiple
= 1;
2146 $dao->is_active
= 1;
2148 while ($dao->fetch()) {
2149 $multipleGroup[$dao->id
] = $dao->title
;
2151 return $multipleGroup;
2155 * Build the metadata tree for the custom group.
2157 * @param string $entityType
2158 * @param array $toReturn
2159 * @param array $subTypes
2160 * @param string $queryString
2161 * @param array $params
2162 * @param string $subType
2165 * @throws \CRM_Core_Exception
2167 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2168 $groupTree = $multipleFieldGroups = [];
2169 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
2170 $customValueTables = [];
2173 while ($crmDAO->fetch()) {
2175 $groupID = $crmDAO->civicrm_custom_group_id
;
2176 $fieldId = $crmDAO->civicrm_custom_field_id
;
2177 if ($crmDAO->civicrm_custom_group_is_multiple
) {
2178 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
2180 // create an array for groups if it does not exist
2181 if (!array_key_exists($groupID, $groupTree)) {
2182 $groupTree[$groupID] = [];
2183 $groupTree[$groupID]['id'] = $groupID;
2185 // populate the group information
2186 foreach ($toReturn['custom_group'] as $fieldName) {
2187 $fullFieldName = "civicrm_custom_group_$fieldName";
2188 if ($fieldName == 'id' ||
2189 is_null($crmDAO->$fullFieldName)
2194 // This is an old bit of code - per the CRM number & probably does not work reliably if
2195 // that one contact sub-type exists.
2196 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2197 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
2199 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2201 $groupTree[$groupID]['fields'] = [];
2203 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = [];
2206 // add the fields now (note - the query row will always contain a field)
2207 // we only reset this once, since multiple values come is as multiple rows
2208 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2209 $groupTree[$groupID]['fields'][$fieldId] = [];
2212 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
2213 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2214 // populate information for a custom field
2215 foreach ($toReturn['custom_field'] as $fieldName) {
2216 $fullFieldName = "civicrm_custom_field_$fieldName";
2217 if ($fieldName == 'id' ||
2218 is_null($crmDAO->$fullFieldName)
2222 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2226 if (!empty($customValueTables)) {
2227 $groupTree['info'] = ['tables' => $customValueTables];
2229 return [$multipleFieldGroups, $groupTree];
2232 public static function getSubTypes(): array {
2234 $activityType = CRM_Core_PseudoConstant
::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
2236 $eventType = CRM_Core_OptionGroup
::values('event_type');
2237 $grantType = CRM_Core_OptionGroup
::values('grant_type');
2238 $campaignTypes = CRM_Campaign_PseudoConstant
::campaignType();
2239 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypes(FALSE);
2240 $participantRole = CRM_Core_OptionGroup
::values('participant_role');
2242 asort($activityType);
2245 asort($membershipType);
2246 asort($participantRole);
2248 $sel2['Event'] = $eventType;
2249 $sel2['Grant'] = $grantType;
2250 $sel2['Activity'] = $activityType;
2251 $sel2['Campaign'] = $campaignTypes;
2252 $sel2['Membership'] = $membershipType;
2253 $sel2['ParticipantRole'] = $participantRole;
2254 $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
2255 $sel2['ParticipantEventType'] = $eventType;
2256 $sel2['Contribution'] = CRM_Contribute_PseudoConstant
::financialType();
2257 $sel2['Relationship'] = CRM_Custom_Form_Group
::getRelationshipTypes();
2259 $sel2['Individual'] = CRM_Contact_BAO_ContactType
::subTypePairs('Individual', FALSE, NULL);
2260 $sel2['Household'] = CRM_Contact_BAO_ContactType
::subTypePairs('Household', FALSE, NULL);
2261 $sel2['Organization'] = CRM_Contact_BAO_ContactType
::subTypePairs('Organization', FALSE, NULL);
2263 CRM_Core_BAO_CustomGroup
::getExtendedObjectTypes($sel2);
2268 * Get the munged entity.
2270 * This is the entity eg. Relationship or the name of the sub entity
2271 * e.g ParticipantRole.
2273 * @param string $extends
2274 * @param int|null $extendsEntityColumn
2278 protected static function getMungedEntity($extends, $extendsEntityColumn = NULL) {
2279 if (!$extendsEntityColumn ||
$extendsEntityColumn === 'null') {
2282 return CRM_Core_OptionGroup
::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name')[$extendsEntityColumn];
2286 * @param int $groupId
2287 * @param int $operation
2288 * @param int|null $userId
2290 public static function checkGroupAccess($groupId, $operation = CRM_Core_Permission
::EDIT
, $userId = NULL): bool {
2291 $allowedGroups = CRM_Core_Permission
::customGroup($operation, FALSE, $userId);
2292 return in_array($groupId, $allowedGroups);