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
{
26 public function __construct() {
27 parent
::__construct();
31 * Takes an associative array and creates a custom group object.
33 * This function is invoked from within the web form layer and also from the api layer
35 * @param array $params
36 * (reference) an assoc array of name/value pairs.
38 * @return CRM_Core_DAO_CustomGroup
41 public static function create(&$params) {
42 // create custom group dao, populate fields and then save.
43 $group = new CRM_Core_DAO_CustomGroup();
44 if (isset($params['title'])) {
45 $group->title
= $params['title'];
48 $extends = CRM_Utils_Array
::value('extends', $params, []);
49 $extendsEntity = $extends[0] ??
NULL;
51 $participantEntities = [
53 'ParticipantEventName',
54 'ParticipantEventType',
57 if (in_array($extendsEntity, $participantEntities)) {
58 $group->extends = 'Participant';
61 $group->extends = $extendsEntity;
64 $group->extends_entity_column_id
= 'null';
65 if (in_array($extendsEntity, $participantEntities)
67 $group->extends_entity_column_id
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $extendsEntity, 'value', 'name');
70 // this is format when form get submit.
71 $extendsChildType = $extends[1] ??
NULL;
72 // lets allow user to pass direct child type value, CRM-6893
73 if (!empty($params['extends_entity_column_value'])) {
74 $extendsChildType = $params['extends_entity_column_value'];
76 if (!CRM_Utils_System
::isNull($extendsChildType)) {
77 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
78 if (CRM_Utils_Array
::value(0, $extends) == 'Relationship') {
79 $extendsChildType = str_replace(['_a_b', '_b_a'], [
82 ], $extendsChildType);
84 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
85 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
86 CRM_Core_DAO
::VALUE_SEPARATOR
;
90 $extendsChildType = 'null';
92 $group->extends_entity_column_value
= $extendsChildType;
94 if (isset($params['id'])) {
95 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
100 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
104 'collapse_adv_display',
111 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
112 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
113 if ($is_public_version) {
114 $fields[] = 'is_public';
116 foreach ($fields as $field) {
117 if (isset($params[$field])) {
118 $group->$field = $params[$field];
121 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
122 $params['max_multiple'] >= '0'
123 ) ?
$params['max_multiple'] : 'null' : 'null';
125 $tableName = $tableNameNeedingIndexUpdate = NULL;
126 if (isset($params['id'])) {
127 $group->id
= $params['id'];
129 if (isset($params['is_multiple'])) {
130 // check whether custom group was changed from single-valued to multiple-valued
131 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
136 // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
137 $paramsIsMultiple = empty($params['is_multiple']) ?
0 : 1;
138 if ($paramsIsMultiple != $isMultiple) {
139 $tableNameNeedingIndexUpdate = CRM_Core_DAO
::getFieldValue(
140 'CRM_Core_DAO_CustomGroup',
148 $group->created_id
= $params['created_id'] ??
NULL;
149 $group->created_date
= $params['created_date'] ??
NULL;
151 // we do this only once, so name never changes
152 if (isset($params['name'])) {
153 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
156 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
159 if (isset($params['table_name'])) {
160 $tableName = $params['table_name'];
162 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
163 // Bad idea. Prevent group creation because it might lead to a broken configuration.
164 throw new CRM_Core_Exception(ts('Cannot create custom table because %1 is already a core table.', ['1' => $tableName]));
169 if (array_key_exists('is_reserved', $params)) {
170 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
172 $op = isset($params['id']) ?
'edit' : 'create';
173 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
175 // enclose the below in a transaction
176 $transaction = new CRM_Core_Transaction();
179 if (!isset($params['id'])) {
180 if (!isset($params['table_name'])) {
181 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 13));
182 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
184 $group->table_name
= $tableName;
185 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
191 // now create the table associated with this group
192 self
::createTable($group);
194 elseif ($tableNameNeedingIndexUpdate) {
195 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array
::value('is_multiple', $params));
198 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
199 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
203 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($extendsEntity));
205 $transaction->commit();
208 CRM_Utils_System
::flushCache();
211 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
214 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
221 * Fetch object based on array of properties.
223 * @param array $params
224 * (reference ) an assoc array of name/value pairs.
225 * @param array $defaults
226 * (reference ) an assoc array to hold the flattened values.
228 * @return CRM_Core_DAO_CustomGroup
230 public static function retrieve(&$params, &$defaults) {
231 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
235 * Update the is_active flag in the db.
238 * Id of the database record.
239 * @param bool $is_active
240 * Value we want to set the is_active field.
243 * true if we found and updated the object, else false
245 public static function setIsActive($id, $is_active) {
247 Civi
::cache('fields')->flush();
248 // reset ACL and system caches.
249 CRM_Core_BAO_Cache
::resetCaches();
252 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
255 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
259 * Determine if given entity (sub)type has any custom groups
261 * @param string $extends
262 * E.g. "Individual", "Activity".
263 * @param int $columnId
264 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
265 * @param string $columnValue
266 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
270 public static function hasCustomGroup($extends, $columnId, $columnValue) {
271 $dao = new CRM_Core_DAO_CustomGroup();
272 $dao->extends = $extends;
273 $dao->extends_entity_column_id
= $columnId;
274 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
275 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
276 //$dao->extends_entity_column_value = $columnValue;
277 return (bool) $dao->find();
281 * Determine if there are any CustomGroups for the given $activityTypeId.
282 * If none found, create one.
284 * @param int $activityTypeId
287 * TRUE if a group is found or created; FALSE on error
289 public static function autoCreateByActivityType($activityTypeId) {
290 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
294 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
297 'extends' => 'Activity',
298 'extends_entity_column_id' => NULL,
299 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded([$activityTypeId]),
300 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
304 $result = civicrm_api('CustomGroup', 'create', $params);
305 return !$result['is_error'];
309 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
310 * This may also include entity specific data values.
312 * An array containing all custom groups and their custom fields is returned.
314 * @param string $entityType
315 * Of the contact whose contact type is needed.
316 * @param array $toReturn
317 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
318 * @param int $entityID
319 * @param int $groupID
320 * @param array $subTypes
321 * @param string $subName
322 * @param bool $fromCache
323 * @param bool $onlySubType
324 * Only return specified subtype or return specified subtype + unrestricted fields.
325 * @param bool $returnAll
326 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
327 * api - through which it is properly tested - so can be refactored with some comfort.)
329 * @param bool $checkPermission
330 * @param string|int $singleRecord
331 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
332 * @param bool $showPublicOnly
335 * Custom field 'tree'.
337 * The returned array is keyed by group id and has the custom group table fields
338 * and a subkey 'fields' holding the specific custom fields.
339 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
340 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
342 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
343 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
344 * With caching the performance impact would be small & the function would be cleaner
346 * @throws \CRM_Core_Exception
348 public static function getTree(
358 $checkPermission = TRUE,
359 $singleRecord = NULL,
360 $showPublicOnly = FALSE
363 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
365 if (!is_array($subTypes)) {
366 if (empty($subTypes)) {
370 if (stristr($subTypes, ',')) {
371 $subTypes = explode(',', $subTypes);
374 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
381 // legacy hardcoded list of data to return
416 'extends_entity_column_id',
417 'extends_entity_column_value',
421 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
422 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
423 if ($is_public_version) {
424 $tableData['custom_group'][] = 'is_public';
426 if (!$toReturn ||
!is_array($toReturn)) {
427 $toReturn = $tableData;
430 // Supply defaults and remove unknown array keys
431 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
432 // Merge in required fields that we must have
433 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
434 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
435 // Validate return fields
436 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
437 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
442 foreach ($toReturn as $tableName => $tableColumn) {
443 foreach ($tableColumn as $columnName) {
444 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
447 $strSelect = "SELECT " . implode(', ', $select);
449 // from, where, order by
451 FROM civicrm_custom_group
452 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
455 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
456 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
457 $entityType == 'Household'
459 $in = "'$entityType', 'Contact'";
461 elseif (strpos($entityType, "'") !== FALSE) {
462 // this allows the calling function to send in multiple entity types
467 $in = "'$entityType'";
473 if (!empty($subTypes)) {
474 foreach ($subTypes as $key => $subType) {
475 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
477 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
479 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
483 WHERE civicrm_custom_group.is_active = 1
484 AND civicrm_custom_field.is_active = 1
485 AND civicrm_custom_group.extends IN ($in)
489 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
490 $params[$sqlParamKey] = [$subName, 'String'];
491 $sqlParamKey = $sqlParamKey +
1;
496 WHERE civicrm_custom_group.is_active = 1
497 AND civicrm_custom_field.is_active = 1
498 AND civicrm_custom_group.extends IN ($in)
501 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
506 // since we want a specific group id we add it to the where clause
507 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
508 $params[$sqlParamKey] = [$groupID, 'Integer'];
511 // since groupID is false we need to show all Inline groups
512 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
514 if ($checkPermission) {
515 // ensure that the user has access to these custom groups
516 $strWhere .= " AND " .
517 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
518 'civicrm_custom_group.'
522 if ($showPublicOnly && $is_public_version) {
523 $strWhere .= "AND civicrm_custom_group.is_public = 1";
527 ORDER BY civicrm_custom_group.weight,
528 civicrm_custom_group.title,
529 civicrm_custom_field.weight,
530 civicrm_custom_field.label
533 // final query string
534 $queryString = "$strSelect $strFrom $strWhere $orderBy";
536 // lets see if we can retrieve the groupTree from cache
537 $cacheString = $queryString;
539 $cacheString .= "_{$groupID}";
542 $cacheString .= "_Inline";
545 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
546 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
547 $cache = CRM_Utils_Cache
::singleton();
549 $groupTree = $cache->get($cacheKey);
550 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
553 if (empty($groupTree)) {
554 list($multipleFieldGroups, $groupTree) = self
::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType);
556 $cache->set($cacheKey, $groupTree);
557 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
559 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
560 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
561 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
562 $singleFieldTables = [];
563 // now that we have all the groups and fields, lets get the values
564 // since we need to know the table and field names
565 // add info to groupTree
567 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
568 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
570 $select = $from = $where = [];
571 $groupTree['info']['where'] = NULL;
573 foreach ($groupTree['info']['tables'] as $table => $fields) {
574 $groupTree['info']['from'][] = $table;
576 "{$table}.id as {$table}_id",
577 "{$table}.entity_id as {$table}_entity_id",
579 foreach ($fields as $column => $dontCare) {
580 $select[] = "{$table}.{$column} as {$table}_{$column}";
582 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
584 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
585 if (in_array($table, $multipleFieldGroups) &&
586 self
::customGroupDataExistsForEntity($entityID, $table)
588 $entityMultipleSelectClauses[$table] = $select;
591 $singleFieldTables[] = $table;
592 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
597 if ($entityID && !empty($singleFieldTables)) {
598 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
600 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
601 if (!empty($multipleFieldTablesWithEntityData)) {
602 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
610 * Clean and validate the filter before it is used in a db query.
612 * @param string $entityType
613 * @param string $subType
616 * @throws \CRM_Core_Exception
618 protected static function validateSubTypeByEntity($entityType, $subType) {
619 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
620 if (is_numeric($subType)) {
624 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
625 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
627 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
628 throw new CRM_Core_Exception('Invalid Entity Filter');
630 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
631 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
632 if (!array_key_exists($subType, $subTypes)) {
633 throw new CRM_Core_Exception('Invalid Filter');
639 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
640 * a WHERE condition for rows that include $value. Use whereListHas().
642 * @param string $column
643 * @param string $value
644 * @param string $delimiter
648 private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
650 $bareValue = trim($value, $delimiter);
651 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
652 return "($column LIKE \"$escapedValue\")";
656 * Check whether the custom group has any data for the given entity.
658 * @param int $entityID
659 * Id of entity for whom we are checking data for.
660 * @param string $table
661 * Table that we are checking.
663 * @param bool $getCount
666 * does this entity have data in this custom table
668 public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
672 WHERE entity_id = $entityID
674 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
676 return $recordExists;
678 return (bool) $recordExists;
682 * Build the group tree for Custom fields which are not 'is_multiple'
684 * The combination of all these fields in one query with a 'using' join was not working for
685 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
686 * mechanism as it seemed to be acceptable in this context
688 * @param array $groupTree
689 * (reference) group tree array which is being built.
690 * @param int $entityID
691 * Id of entity for whom the tree is being build up.
692 * @param array $entitySingleSelectClauses
693 * Array of select clauses relevant to the entity.
694 * @param array $singleFieldTablesWithEntityData
695 * Array of tables in which this entity has data.
697 public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
698 $select = implode(', ', $entitySingleSelectClauses);
699 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
700 foreach ($singleFieldTablesWithEntityData as $table) {
701 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
707 WHERE first.entity_id = $entityID
709 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
713 * Build the group tree for Custom fields which are 'is_multiple'
715 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
717 * @param array $groupTree
718 * (reference) group tree array which is being built.
719 * @param int $entityID
720 * Id of entity for whom the tree is being build up.
721 * @param array $entityMultipleSelectClauses
722 * Array of select clauses relevant to the entity.
723 * @param array $multipleFieldTablesWithEntityData
724 * Array of tables in which this entity has data.
725 * @param string|int $singleRecord
726 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
728 public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
729 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
730 $select = implode(',', $selectClauses);
734 WHERE entity_id = $entityID
737 $offset = $singleRecord - 1;
738 $query .= " LIMIT {$offset}, 1";
740 self
::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
745 * Build the tree entity data - starting from a query retrieving the custom fields build the group
746 * tree data for the relevant entity (entity is included in the query).
748 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
750 * @param array $groupTree
751 * (reference) group tree array which is being built.
752 * @param string $query
753 * @param array $includedTables
754 * Tables to include - required because the function (for historical reasons).
755 * iterates through the group tree
756 * @param string|int $singleRecord
757 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
759 public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
760 $dao = CRM_Core_DAO
::executeQuery($query);
761 while ($dao->fetch()) {
762 foreach ($groupTree as $groupID => $group) {
763 if ($groupID === 'info') {
766 $table = $groupTree[$groupID]['table_name'];
767 //working from the groupTree instead of the table list means we have to iterate & exclude.
768 // this could possibly be re-written as other parts of the function have been refactored
769 // for now we just check if the given table is to be included in this function
770 if (!in_array($table, $includedTables)) {
773 foreach ($group['fields'] as $fieldID => $dontCare) {
774 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
781 * Build the entity-specific custom data into the group tree on a per-field basis
784 * Object representing the custom field to be populated into the groupTree.
785 * @param array $groupTree
786 * (reference) the group tree being build.
787 * @param string $table
789 * @param int $groupID
791 * @param int $fieldID
793 * @param string|int $singleRecord
794 * holds 'new' or id if loading view/edit/copy for a single record.
796 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
797 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
798 $idName = "{$table}_id";
799 $fieldName = "{$table}_{$column}";
800 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
801 if ($dataType == 'File') {
802 if (isset($dao->$fieldName)) {
803 $config = CRM_Core_Config
::singleton();
804 $fileDAO = new CRM_Core_DAO_File();
805 $fileDAO->id
= $dao->$fieldName;
807 if ($fileDAO->find(TRUE)) {
808 $entityIDName = "{$table}_entity_id";
809 $fileHash = CRM_Core_BAO_File
::generateFileHash($dao->$entityIDName, $fileDAO->id
);
810 $customValue['id'] = $dao->$idName;
811 $customValue['data'] = $fileDAO->uri
;
812 $customValue['fid'] = $fileDAO->id
;
813 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
814 $customValue['displayURL'] = NULL;
815 $deleteExtra = ts('Are you sure you want to delete attached file.');
817 CRM_Core_Action
::DELETE
=> [
818 'name' => ts('Delete Attached File'),
819 'url' => 'civicrm/file',
820 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
821 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
822 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
825 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
826 CRM_Core_Action
::DELETE
,
828 'id' => $fileDAO->id
,
829 'eid' => $dao->$entityIDName,
835 'file.manage.delete',
839 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
840 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
841 if ($fileDAO->mime_type
== "image/jpeg" ||
842 $fileDAO->mime_type
== "image/pjpeg" ||
843 $fileDAO->mime_type
== "image/gif" ||
844 $fileDAO->mime_type
== "image/x-png" ||
845 $fileDAO->mime_type
== "image/png"
847 $customValue['displayURL'] = $customValue['fileURL'];
848 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
853 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
855 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId);
856 if ($path && file_exists($path)) {
857 list($imageWidth, $imageHeight) = getimagesize($path);
858 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
859 $customValue['imageThumbWidth'] = $imageThumbWidth;
860 $customValue['imageThumbHeight'] = $imageThumbHeight;
867 'id' => $dao->$idName,
874 'id' => $dao->$idName,
875 'data' => $dao->$fieldName,
879 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
880 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
882 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
883 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
885 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
886 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
889 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
894 * Get the group title.
902 public static function getTitle($id) {
903 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
907 * Get custom group details for a group.
909 * An array containing custom group details (including their custom field) is returned.
911 * @param int $groupId
912 * Group id whose details are needed.
913 * @param bool $searchable
914 * Is this field searchable.
915 * @param array $extends
916 * Which table does it extend if any.
918 * @param bool $inSelector
921 * array consisting of all group and field details
923 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
927 // using tableData to build the queryString
929 'civicrm_custom_field' => [
953 'civicrm_custom_group' => [
960 'collapse_adv_display',
962 'extends_entity_column_value',
970 foreach ($tableData as $tableName => $tableColumn) {
971 foreach ($tableColumn as $columnName) {
972 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
975 $select = 'SELECT ' . implode(', ', $s);
977 // from, where, order by
978 $from = " FROM civicrm_custom_field, civicrm_custom_group";
979 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
980 AND civicrm_custom_group.is_active = 1
981 AND civicrm_custom_field.is_active = 1 ";
983 $params[1] = [$groupId, 'Integer'];
984 $where .= " AND civicrm_custom_group.id = %1";
988 $where .= " AND civicrm_custom_field.is_searchable = 1";
992 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
997 foreach ($extends as $e) {
998 $clause[] = "civicrm_custom_group.extends = '$e'";
1000 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1002 //include case activities customdata if case is enabled
1003 if (in_array('Activity', $extends)) {
1004 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1005 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1006 $params[2] = [CRM_Core_DAO
::VALUE_SEPARATOR
, 'String'];
1010 // ensure that the user has access to these custom groups
1012 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1013 'civicrm_custom_group.'
1016 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1018 // final query string
1019 $queryString = $select . $from . $where . $orderBy;
1022 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1025 while ($crmDAO->fetch()) {
1026 $groupId = $crmDAO->civicrm_custom_group_id
;
1027 $fieldId = $crmDAO->civicrm_custom_field_id
;
1029 // create an array for groups if it does not exist
1030 if (!array_key_exists($groupId, $groupTree)) {
1031 $groupTree[$groupId] = [];
1032 $groupTree[$groupId]['id'] = $groupId;
1034 foreach ($tableData['civicrm_custom_group'] as $v) {
1035 $fullField = "civicrm_custom_group_" . $v;
1037 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1041 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1044 $groupTree[$groupId]['fields'] = [];
1047 // add the fields now (note - the query row will always contain a field)
1048 $groupTree[$groupId]['fields'][$fieldId] = [];
1049 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1051 foreach ($tableData['civicrm_custom_field'] as $v) {
1052 $fullField = "civicrm_custom_field_" . $v;
1053 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1056 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1064 * @param $entityType
1066 * @param string $cidToken
1070 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1072 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1074 // get 'Tab' and 'Tab with table' groups
1075 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1076 $customGroupDAO->whereAdd("is_active = 1");
1078 // add whereAdd for entity type
1079 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1083 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1084 $customGroupDAO->whereAdd($permissionClause);
1087 $customGroupDAO->orderBy('weight');
1088 $customGroupDAO->find();
1090 // process each group with menu tab
1091 while ($customGroupDAO->fetch()) {
1093 $group['id'] = $customGroupDAO->id
;
1094 $group['path'] = $path;
1095 $group['title'] = "$customGroupDAO->title";
1096 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1097 $group['extra'] = ['gid' => $customGroupDAO->id
];
1098 $group['table_name'] = $customGroupDAO->table_name
;
1099 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1100 $group['icon'] = $customGroupDAO->icon
;
1108 * Get the table name for the entity type
1109 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1110 * tableName is 'civicrm_contact'
1112 * @param string $entityType
1113 * What entity are we extending here ?.
1118 * @see _apachesolr_civiAttachments_dereference_file_parent
1120 public static function getTableNameByEntityName($entityType) {
1122 switch ($entityType) {
1126 case 'Organization':
1127 $tableName = 'civicrm_contact';
1130 case 'Contribution':
1131 $tableName = 'civicrm_contribution';
1135 $tableName = 'civicrm_group';
1138 // DRAFTING: Verify if we cannot make it pluggable
1141 $tableName = 'civicrm_activity';
1144 case 'Relationship':
1145 $tableName = 'civicrm_relationship';
1149 $tableName = 'civicrm_membership';
1153 $tableName = 'civicrm_participant';
1157 $tableName = 'civicrm_event';
1161 $tableName = 'civicrm_grant';
1164 // need to add cases for Location, Address
1171 * Get a list of custom groups which extend a given entity type.
1172 * If there are custom-groups which only apply to certain subtypes,
1173 * those WILL be included.
1175 * @param string $entityType
1177 * @return CRM_Core_DAO_CustomGroup
1179 public static function getAllCustomGroupsByBaseEntity($entityType) {
1180 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1181 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1182 return $customGroupDAO;
1186 * Add the whereAdd clause for the DAO depending on the type of entity
1187 * the custom group is extending.
1189 * @param object $customGroupDAO
1190 * @param string $entityType
1191 * What entity are we extending here ?.
1193 * @param int $entityID
1194 * @param bool $allSubtypes
1196 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1197 $addSubtypeClause = FALSE;
1198 // This function isn't really accessible with user data but since the string
1199 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1201 $entityType = CRM_Core_DAO
::escapeString($entityType);
1203 switch ($entityType) {
1205 // if contact, get all related to contact
1206 $extendList = "'Contact','Individual','Household','Organization'";
1207 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1208 if (!$allSubtypes) {
1209 $addSubtypeClause = TRUE;
1215 case 'Organization':
1216 // is I/H/O then get I/H/O and contact
1217 $extendList = "'Contact','$entityType'";
1218 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1219 if (!$allSubtypes) {
1220 $addSubtypeClause = TRUE;
1225 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1229 if ($addSubtypeClause) {
1230 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1232 if (!empty($csType)) {
1233 $subtypeClause = [];
1234 foreach ($csType as $subtype) {
1235 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1236 CRM_Core_DAO
::VALUE_SEPARATOR
;
1237 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1239 $subtypeClause[] = "extends_entity_column_value IS NULL";
1240 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1244 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1250 * Delete the Custom Group.
1252 * @param CRM_Core_BAO_CustomGroup $group
1253 * Custom group object.
1254 * @param bool $force
1255 * whether to force the deletion, even if there are custom fields.
1258 * False if field exists for this group, true if group gets deleted.
1260 public static function deleteGroup($group, $force = FALSE) {
1262 //check whether this contain any custom fields
1263 $customField = new CRM_Core_DAO_CustomField();
1264 $customField->custom_group_id
= $group->id
;
1265 $customField->find();
1267 // return early if there are custom fields and we're not
1268 // forcing the delete, otherwise delete the fields one by one
1269 while ($customField->fetch()) {
1273 CRM_Core_BAO_CustomField
::deleteField($customField);
1276 // drop the table associated with this custom group
1277 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1279 //delete custom group
1282 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1290 * @param array $groupTree
1291 * @param array $defaults
1292 * @param bool $viewMode
1293 * @param bool $inactiveNeeded
1294 * @param int $action
1296 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1297 foreach ($groupTree as $id => $group) {
1298 if (!isset($group['fields'])) {
1301 foreach ($group['fields'] as $field) {
1302 if (isset($field['element_value'])) {
1303 $value = $field['element_value'];
1305 elseif (isset($field['default_value']) &&
1306 ($action != CRM_Core_Action
::UPDATE ||
1308 !array_key_exists('element_value', $field)
1311 $value = $viewMode ?
NULL : $field['default_value'];
1317 if (empty($field['element_name'])) {
1321 $elementName = $field['element_name'];
1322 $serialize = CRM_Core_BAO_CustomField
::isSerialized($field);
1325 if ($field['data_type'] != 'Country' && $field['data_type'] != 'StateProvince') {
1326 $defaults[$elementName] = [];
1327 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1329 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1330 if (isset($value)) {
1331 foreach ($customOption as $customValue => $customLabel) {
1332 if (in_array($customValue, $checkedData)) {
1333 if ($field['html_type'] == 'CheckBox') {
1334 $defaults[$elementName][$customValue] = 1;
1337 $defaults[$elementName][$customValue] = $customValue;
1341 $defaults[$elementName][$customValue] = 0;
1347 if (isset($field['customValue']['data'])) {
1348 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1349 foreach ($customOption as $val) {
1350 if (in_array($val['value'], $checkedData)) {
1351 if ($field['html_type'] == 'CheckBox') {
1352 $defaults[$elementName][$val['value']] = 1;
1355 $defaults[$elementName][$val['value']] = $val['value'];
1359 $defaults[$elementName][$val['value']] = 0;
1364 // Values may be "array strings" or actual arrays. Handle both.
1365 if (is_array($value) && count($value)) {
1366 CRM_Utils_Array
::formatArrayKeys($value);
1367 $checkedValue = $value;
1370 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1372 foreach ($customOption as $val) {
1373 if (in_array($val['value'], $checkedValue)) {
1374 if ($field['html_type'] == 'CheckBox') {
1375 $defaults[$elementName][$val['value']] = 1;
1378 $defaults[$elementName][$val['value']] = $val['value'];
1386 if (isset($value)) {
1387 // Values may be "array strings" or actual arrays. Handle both.
1388 if (is_array($value) && count($value)) {
1389 CRM_Utils_Array
::formatArrayKeys($value);
1390 $checkedValue = $value;
1393 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
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
::format($value, NULL, '%a');
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 bulding 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 // add field information
1822 foreach ($value['fields'] as $k => $properties) {
1823 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1824 if (isset($properties['customValue']) &&
1825 !CRM_Utils_System
::isNull($properties['customValue']) &&
1826 !isset($properties['element_value'])
1828 if (isset($properties['customValue'][$groupCount])) {
1829 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1830 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1831 if ($properties['data_type'] === 'File') {
1832 $properties['element_value'] = $properties['customValue'][$groupCount];
1833 $uploadNames[] = $properties['element_name'];
1836 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1840 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1841 $formValues[$properties['element_name']] = $value;
1843 elseif (isset($submittedValues[$properties['element_name']])) {
1844 $properties['element_value'] = $submittedValues[$properties['element_name']];
1846 unset($properties['customValue']);
1847 $formattedGroupTree[$key]['fields'][$k] = $properties;
1852 if (count($formValues)) {
1853 $qf = $form->get('qfKey');
1854 $form->assign('qfKey', $qf);
1855 Civi
::cache('customData')->set($qf, $formValues);
1858 // hack for field type File
1859 $formUploadNames = $form->get('uploadNames');
1860 if (is_array($formUploadNames)) {
1861 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1864 $form->set('uploadNames', $uploadNames);
1867 return $formattedGroupTree;
1871 * Build custom data view.
1873 * @param CRM_Core_Form|CRM_Core_Page $form
1875 * @param array $groupTree
1876 * @param bool $returnCount
1877 * True if customValue count needs to be returned.
1879 * @param null $prefix
1880 * @param int $customValueId
1881 * @param int $entityId
1884 * @throws \CRM_Core_Exception
1886 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1888 foreach ($groupTree as $key => $group) {
1889 if ($key === 'info') {
1893 foreach ($group['fields'] as $k => $properties) {
1894 $groupID = $group['id'];
1895 if (!empty($properties['customValue'])) {
1896 foreach ($properties['customValue'] as $values) {
1897 if (!empty($customValueId) && $customValueId != $values['id']) {
1900 $details[$groupID][$values['id']]['title'] = $group['title'] ??
NULL;
1901 $details[$groupID][$values['id']]['name'] = $group['name'] ??
NULL;
1902 $details[$groupID][$values['id']]['help_pre'] = $group['help_pre'] ??
NULL;
1903 $details[$groupID][$values['id']]['help_post'] = $group['help_post'] ??
NULL;
1904 $details[$groupID][$values['id']]['collapse_display'] = $group['collapse_display'] ??
NULL;
1905 $details[$groupID][$values['id']]['collapse_adv_display'] = $group['collapse_adv_display'] ??
NULL;
1906 $details[$groupID][$values['id']]['style'] = $group['style'] ??
NULL;
1907 $details[$groupID][$values['id']]['fields'][$k] = [
1908 'field_title' => $properties['label'] ??
NULL,
1909 'field_type' => $properties['html_type'] ??
NULL,
1910 'field_data_type' => $properties['data_type'] ??
NULL,
1911 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1912 'options_per_line' => $properties['options_per_line'] ??
NULL,
1914 // editable = whether this set contains any non-read-only fields
1915 if (!isset($details[$groupID][$values['id']]['editable'])) {
1916 $details[$groupID][$values['id']]['editable'] = FALSE;
1918 if (empty($properties['is_view'])) {
1919 $details[$groupID][$values['id']]['editable'] = TRUE;
1921 // also return contact reference contact id if user has view all or edit all contacts perm
1922 if ((CRM_Core_Permission
::check('view all contacts') ||
1923 CRM_Core_Permission
::check('edit all contacts'))
1925 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1928 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = $values['data'] ??
NULL;
1933 $details[$groupID][0]['title'] = $group['title'] ??
NULL;
1934 $details[$groupID][0]['name'] = $group['name'] ??
NULL;
1935 $details[$groupID][0]['help_pre'] = $group['help_pre'] ??
NULL;
1936 $details[$groupID][0]['help_post'] = $group['help_post'] ??
NULL;
1937 $details[$groupID][0]['collapse_display'] = $group['collapse_display'] ??
NULL;
1938 $details[$groupID][0]['collapse_adv_display'] = $group['collapse_adv_display'] ??
NULL;
1939 $details[$groupID][0]['style'] = $group['style'] ??
NULL;
1940 $details[$groupID][0]['fields'][$k] = ['field_title' => CRM_Utils_Array
::value('label', $properties)];
1946 // return a single value count if group id is passed to function
1947 // else return a groupId and count mapped array
1949 return count($details[$gID]);
1953 foreach ($details as $key => $value) {
1954 $countValue[$key] = count($details[$key]);
1960 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1966 * Get the custom group titles by custom field ids.
1968 * @param array $fieldIds
1969 * Array of custom field ids.
1971 * @return array|NULL
1972 * array consisting of groups and fields labels with ids.
1974 public static function getGroupTitles($fieldIds) {
1975 if (!is_array($fieldIds) && empty($fieldIds)) {
1980 $fIds = "(" . implode(',', $fieldIds) . ")";
1983 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1984 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1985 FROM civicrm_custom_group, civicrm_custom_field
1986 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1987 AND civicrm_custom_field.id IN {$fIds}";
1989 $dao = CRM_Core_DAO
::executeQuery($query);
1990 while ($dao->fetch()) {
1991 $groupLabels[$dao->fieldID
] = [
1992 'fieldID' => $dao->fieldID
,
1993 'fieldLabel' => $dao->fieldLabel
,
1994 'groupID' => $dao->groupID
,
1995 'groupTitle' => $dao->groupTitle
,
1999 return $groupLabels;
2002 public static function dropAllTables() {
2003 $query = "SELECT table_name FROM civicrm_custom_group";
2004 $dao = CRM_Core_DAO
::executeQuery($query);
2006 while ($dao->fetch()) {
2007 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2008 CRM_Core_DAO
::executeQuery($query);
2013 * Check whether custom group is empty or not.
2019 * true if empty otherwise false.
2021 public static function isGroupEmpty($gID) {
2026 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2031 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2032 $value = CRM_Core_DAO
::singleValueQuery($query);
2034 if (empty($value)) {
2042 * Get the list of types for objects that a custom group extends to.
2044 * @param array $types
2045 * Var which should have the list appended.
2049 * @throws \Exception
2051 public static function getExtendedObjectTypes(&$types = []) {
2052 static $flag = FALSE, $objTypes = [];
2056 CRM_Core_OptionValue
::getValues(['name' => 'cg_extend_objects'], $extendObjs, 'weight', TRUE);
2058 foreach ($extendObjs as $ovId => $ovValues) {
2059 if ($ovValues['description']) {
2060 // description is expected to be a callback func to subtypes
2061 list($callback, $args) = explode(';', trim($ovValues['description']));
2067 if (!is_array($args)) {
2068 throw new CRM_Core_Exception('Arg is not of type array');
2071 list($className) = explode('::', $callback);
2072 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
2074 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2080 $types = array_merge($types, $objTypes);
2085 * @param int $customGroupId
2086 * @param int $entityId
2090 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2091 // check whether the group is multiple
2092 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2093 $isMultiple = (bool) $isMultiple;
2094 $hasReachedMax = FALSE;
2096 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2098 if (!$maxMultiple) {
2099 $hasReachedMax = FALSE;
2102 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2103 // count the number of entries for a entity
2104 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2105 $params = [1 => [$entityId, 'Integer']];
2106 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2108 if ($count >= $maxMultiple) {
2109 $hasReachedMax = TRUE;
2113 return $hasReachedMax;
2119 public static function getMultipleFieldGroup() {
2120 $multipleGroup = [];
2121 $dao = new CRM_Core_DAO_CustomGroup();
2122 $dao->is_multiple
= 1;
2123 $dao->is_active
= 1;
2125 while ($dao->fetch()) {
2126 $multipleGroup[$dao->id
] = $dao->title
;
2128 return $multipleGroup;
2132 * Build the metadata tree for the custom group.
2134 * @param string $entityType
2135 * @param array $toReturn
2136 * @param array $subTypes
2137 * @param string $queryString
2138 * @param array $params
2139 * @param string $subType
2142 * @throws \CRM_Core_Exception
2144 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2145 $groupTree = $multipleFieldGroups = [];
2146 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
2147 $customValueTables = [];
2150 while ($crmDAO->fetch()) {
2152 $groupID = $crmDAO->civicrm_custom_group_id
;
2153 $fieldId = $crmDAO->civicrm_custom_field_id
;
2154 if ($crmDAO->civicrm_custom_group_is_multiple
) {
2155 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
2157 // create an array for groups if it does not exist
2158 if (!array_key_exists($groupID, $groupTree)) {
2159 $groupTree[$groupID] = [];
2160 $groupTree[$groupID]['id'] = $groupID;
2162 // populate the group information
2163 foreach ($toReturn['custom_group'] as $fieldName) {
2164 $fullFieldName = "civicrm_custom_group_$fieldName";
2165 if ($fieldName == 'id' ||
2166 is_null($crmDAO->$fullFieldName)
2171 // This is an old bit of code - per the CRM number & probably does not work reliably if
2172 // that one contact sub-type exists.
2173 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2174 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
2176 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2178 $groupTree[$groupID]['fields'] = [];
2180 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = [];
2183 // add the fields now (note - the query row will always contain a field)
2184 // we only reset this once, since multiple values come is as multiple rows
2185 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2186 $groupTree[$groupID]['fields'][$fieldId] = [];
2189 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
2190 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2191 // populate information for a custom field
2192 foreach ($toReturn['custom_field'] as $fieldName) {
2193 $fullFieldName = "civicrm_custom_field_$fieldName";
2194 if ($fieldName == 'id' ||
2195 is_null($crmDAO->$fullFieldName)
2199 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2203 if (!empty($customValueTables)) {
2204 $groupTree['info'] = ['tables' => $customValueTables];
2206 return [$multipleFieldGroups, $groupTree];