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 $extendsChildType = NULL;
49 // lets allow user to pass direct child type value, CRM-6893
50 if (!empty($params['extends_entity_column_value'])) {
51 $extendsChildType = $params['extends_entity_column_value'];
53 if (!CRM_Utils_System
::isNull($extendsChildType)) {
54 $b = self
::getMungedEntity($params['extends'], $params['extends_entity_column_id'] ??
NULL);
55 $registeredSubTypes = self
::getSubTypes()[$b];
56 if (is_array($extendsChildType)) {
57 foreach ($extendsChildType as $childType) {
58 if (!array_key_exists($childType, $registeredSubTypes) && !in_array($childType, $registeredSubTypes, TRUE)) {
59 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
64 if (!array_key_exists($extendsChildType, $registeredSubTypes) && !in_array($extendsChildType, $registeredSubTypes, TRUE)) {
65 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
67 $extendsChildType = [$extendsChildType];
69 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
70 if ($params['extends'] == 'Relationship') {
71 $extendsChildType = str_replace(['_a_b', '_b_a'], [
74 ], $extendsChildType);
76 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
77 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
78 CRM_Core_DAO
::VALUE_SEPARATOR
;
82 $extendsChildType = 'null';
84 $group->extends_entity_column_value
= $extendsChildType;
86 if (isset($params['id'])) {
87 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
92 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
96 'collapse_adv_display',
102 'extends_entity_column_id',
105 $current_db_version = CRM_Core_BAO_Domain
::version();
106 $is_public_version = version_compare($current_db_version, '4.7.19', '>=');
107 if ($is_public_version) {
108 $fields[] = 'is_public';
110 foreach ($fields as $field) {
111 if (isset($params[$field])) {
112 $group->$field = $params[$field];
115 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
116 $params['max_multiple'] >= '0'
117 ) ?
$params['max_multiple'] : 'null' : 'null';
119 $tableName = $tableNameNeedingIndexUpdate = NULL;
120 if (isset($params['id'])) {
121 $group->id
= $params['id'];
123 if (isset($params['is_multiple'])) {
124 // check whether custom group was changed from single-valued to multiple-valued
125 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
130 // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
131 $paramsIsMultiple = empty($params['is_multiple']) ?
0 : 1;
132 if ($paramsIsMultiple != $isMultiple) {
133 $tableNameNeedingIndexUpdate = CRM_Core_DAO
::getFieldValue(
134 'CRM_Core_DAO_CustomGroup',
142 $group->created_id
= $params['created_id'] ??
NULL;
143 $group->created_date
= $params['created_date'] ??
NULL;
145 // Process name only during create, so it never changes
146 if (!empty($params['name'])) {
147 $group->name
= CRM_Utils_String
::munge($params['name']);
150 $group->name
= CRM_Utils_String
::munge($group->title
);
153 self
::validateCustomGroupName($group);
155 if (isset($params['table_name'])) {
156 $tableName = $params['table_name'];
158 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
159 // Bad idea. Prevent group creation because it might lead to a broken configuration.
160 throw new CRM_Core_Exception(ts('Cannot create custom table because %1 is already a core table.', ['1' => $tableName]));
165 if (array_key_exists('is_reserved', $params)) {
166 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
168 $op = isset($params['id']) ?
'edit' : 'create';
169 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
171 // enclose the below in a transaction
172 $transaction = new CRM_Core_Transaction();
175 if (!isset($params['id'])) {
176 if (!isset($params['table_name'])) {
177 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 13));
178 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
180 $group->table_name
= $tableName;
181 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
187 // now create the table associated with this group
188 self
::createTable($group);
190 elseif ($tableNameNeedingIndexUpdate) {
191 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array
::value('is_multiple', $params));
194 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
195 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
199 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends']));
201 $transaction->commit();
204 CRM_Utils_System
::flushCache();
207 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
210 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
217 * Fetch object based on array of properties.
219 * @param array $params
220 * (reference ) an assoc array of name/value pairs.
221 * @param array $defaults
222 * (reference ) an assoc array to hold the flattened values.
224 * @return CRM_Core_DAO_CustomGroup
226 public static function retrieve(&$params, &$defaults) {
227 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
231 * Ensure group name does not conflict with an existing field
233 * @param CRM_Core_DAO_CustomGroup $group
235 public static function validateCustomGroupName(CRM_Core_DAO_CustomGroup
$group) {
236 $extends = in_array($group->extends, CRM_Contact_BAO_ContactType
::basicTypes(TRUE)) ?
'Contact' : $group->extends;
237 $extendsDAO = CRM_Core_DAO_AllCoreTables
::getFullName($extends);
239 $fields = array_column($extendsDAO::fields(), 'name');
240 if (in_array($group->name
, $fields)) {
247 * Update the is_active flag in the db.
250 * Id of the database record.
251 * @param bool $is_active
252 * Value we want to set the is_active field.
255 * true if we found and updated the object, else false
257 public static function setIsActive($id, $is_active) {
259 Civi
::cache('fields')->flush();
260 // reset ACL and system caches.
261 CRM_Core_BAO_Cache
::resetCaches();
264 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
267 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
271 * Determine if given entity (sub)type has any custom groups
273 * @param string $extends
274 * E.g. "Individual", "Activity".
275 * @param int $columnId
276 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
277 * @param string $columnValue
278 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
282 public static function hasCustomGroup($extends, $columnId, $columnValue) {
283 $dao = new CRM_Core_DAO_CustomGroup();
284 $dao->extends = $extends;
285 $dao->extends_entity_column_id
= $columnId;
286 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
287 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
288 //$dao->extends_entity_column_value = $columnValue;
289 return (bool) $dao->find();
293 * Determine if there are any CustomGroups for the given $activityTypeId.
294 * If none found, create one.
296 * @param int $activityTypeId
299 * TRUE if a group is found or created; FALSE on error
301 public static function autoCreateByActivityType($activityTypeId) {
302 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
306 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
309 'extends' => 'Activity',
310 'extends_entity_column_id' => NULL,
311 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded([$activityTypeId]),
312 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
316 $result = civicrm_api('CustomGroup', 'create', $params);
317 return !$result['is_error'];
321 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
322 * This may also include entity specific data values.
324 * An array containing all custom groups and their custom fields is returned.
326 * @param string $entityType
327 * Of the contact whose contact type is needed.
328 * @param array $toReturn
329 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
330 * @param int $entityID
331 * @param int $groupID
332 * @param array $subTypes
333 * @param string $subName
334 * @param bool $fromCache
335 * @param bool $onlySubType
336 * Only return specified subtype or return specified subtype + unrestricted fields.
337 * @param bool $returnAll
338 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
339 * api - through which it is properly tested - so can be refactored with some comfort.)
340 * @param bool|int $checkPermission
341 * Either a CRM_Core_Permission constant or FALSE to disable checks
342 * @param string|int $singleRecord
343 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
344 * @param bool $showPublicOnly
347 * Custom field 'tree'.
349 * The returned array is keyed by group id and has the custom group table fields
350 * and a subkey 'fields' holding the specific custom fields.
351 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
352 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
354 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
355 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
356 * With caching the performance impact would be small & the function would be cleaner
358 * @throws \CRM_Core_Exception
360 public static function getTree(
370 $checkPermission = CRM_Core_Permission
::EDIT
,
371 $singleRecord = NULL,
372 $showPublicOnly = FALSE
374 if ($checkPermission === TRUE) {
375 CRM_Core_Error
::deprecatedWarning('Unexpected TRUE passed to CustomGroup::getTree $checkPermission param.');
376 $checkPermission = CRM_Core_Permission
::EDIT
;
379 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
381 if (!is_array($subTypes)) {
382 if (empty($subTypes)) {
386 if (stristr($subTypes, ',')) {
387 $subTypes = explode(',', $subTypes);
390 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
397 // legacy hardcoded list of data to return
431 'extends_entity_column_id',
432 'extends_entity_column_value',
436 $current_db_version = CRM_Core_BAO_Domain
::version();
437 $is_public_version = version_compare($current_db_version, '4.7.19', '>=');
438 $serialize_version = version_compare($current_db_version, '5.27.alpha1', '>=');
439 if ($is_public_version) {
440 $tableData['custom_group'][] = 'is_public';
442 if ($serialize_version) {
443 $tableData['custom_field'][] = 'serialize';
445 if (!$toReturn ||
!is_array($toReturn)) {
446 $toReturn = $tableData;
449 // Supply defaults and remove unknown array keys
450 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
451 // Merge in required fields that we must have
452 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
453 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
454 // Validate return fields
455 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
456 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
461 foreach ($toReturn as $tableName => $tableColumn) {
462 foreach ($tableColumn as $columnName) {
463 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
466 $strSelect = "SELECT " . implode(', ', $select);
468 // from, where, order by
470 FROM civicrm_custom_group
471 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
474 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
475 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
476 $entityType == 'Household'
478 $in = "'$entityType', 'Contact'";
480 elseif (strpos($entityType, "'") !== FALSE) {
481 // this allows the calling function to send in multiple entity types
486 $in = "'$entityType'";
492 if (!empty($subTypes)) {
493 foreach ($subTypes as $key => $subType) {
494 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
496 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
498 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
502 WHERE civicrm_custom_group.is_active = 1
503 AND civicrm_custom_field.is_active = 1
504 AND civicrm_custom_group.extends IN ($in)
508 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
509 $params[$sqlParamKey] = [$subName, 'String'];
510 $sqlParamKey = $sqlParamKey +
1;
515 WHERE civicrm_custom_group.is_active = 1
516 AND civicrm_custom_field.is_active = 1
517 AND civicrm_custom_group.extends IN ($in)
520 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
525 // since we want a specific group id we add it to the where clause
526 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
527 $params[$sqlParamKey] = [$groupID, 'Integer'];
530 // since groupID is false we need to show all Inline groups
531 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
533 if ($checkPermission) {
534 // ensure that the user has access to these custom groups
535 $strWhere .= " AND " .
536 CRM_Core_Permission
::customGroupClause($checkPermission,
537 'civicrm_custom_group.'
541 if ($showPublicOnly && $is_public_version) {
542 $strWhere .= "AND civicrm_custom_group.is_public = 1";
546 ORDER BY civicrm_custom_group.weight,
547 civicrm_custom_group.title,
548 civicrm_custom_field.weight,
549 civicrm_custom_field.label
552 // final query string
553 $queryString = "$strSelect $strFrom $strWhere $orderBy";
555 // lets see if we can retrieve the groupTree from cache
556 $cacheString = $queryString;
558 $cacheString .= "_{$groupID}";
561 $cacheString .= "_Inline";
564 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
565 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
566 $cache = CRM_Utils_Cache
::singleton();
568 $groupTree = $cache->get($cacheKey);
569 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
572 if (empty($groupTree)) {
573 list($multipleFieldGroups, $groupTree) = self
::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType);
575 $cache->set($cacheKey, $groupTree);
576 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
578 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
579 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
580 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
581 $singleFieldTables = [];
582 // now that we have all the groups and fields, lets get the values
583 // since we need to know the table and field names
584 // add info to groupTree
586 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
587 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
589 $select = $from = $where = [];
590 $groupTree['info']['where'] = NULL;
592 foreach ($groupTree['info']['tables'] as $table => $fields) {
593 $groupTree['info']['from'][] = $table;
595 "{$table}.id as {$table}_id",
596 "{$table}.entity_id as {$table}_entity_id",
598 foreach ($fields as $column => $dontCare) {
599 $select[] = "{$table}.{$column} as {$table}_{$column}";
601 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
603 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
604 if (in_array($table, $multipleFieldGroups) &&
605 self
::customGroupDataExistsForEntity($entityID, $table)
607 $entityMultipleSelectClauses[$table] = $select;
610 $singleFieldTables[] = $table;
611 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
616 if ($entityID && !empty($singleFieldTables)) {
617 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
619 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
620 if (!empty($multipleFieldTablesWithEntityData)) {
621 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
629 * Clean and validate the filter before it is used in a db query.
631 * @param string $entityType
632 * @param string $subType
635 * @throws \CRM_Core_Exception
637 protected static function validateSubTypeByEntity($entityType, $subType) {
638 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
639 if (is_numeric($subType)) {
643 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
644 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
646 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
647 throw new CRM_Core_Exception('Invalid Entity Filter');
649 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
650 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
651 if (!array_key_exists($subType, $subTypes)) {
652 throw new CRM_Core_Exception('Invalid Filter');
658 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
659 * a WHERE condition for rows that include $value. Use whereListHas().
661 * @param string $column
662 * @param string $value
663 * @param string $delimiter
667 private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
669 $bareValue = trim($value, $delimiter);
670 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
671 return "($column LIKE \"$escapedValue\")";
675 * Check whether the custom group has any data for the given entity.
677 * @param int $entityID
678 * Id of entity for whom we are checking data for.
679 * @param string $table
680 * Table that we are checking.
682 * @param bool $getCount
685 * does this entity have data in this custom table
687 public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
691 WHERE entity_id = $entityID
693 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
695 return $recordExists;
697 return (bool) $recordExists;
701 * Build the group tree for Custom fields which are not 'is_multiple'
703 * The combination of all these fields in one query with a 'using' join was not working for
704 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
705 * mechanism as it seemed to be acceptable in this context
707 * @param array $groupTree
708 * (reference) group tree array which is being built.
709 * @param int $entityID
710 * Id of entity for whom the tree is being build up.
711 * @param array $entitySingleSelectClauses
712 * Array of select clauses relevant to the entity.
713 * @param array $singleFieldTablesWithEntityData
714 * Array of tables in which this entity has data.
716 public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
717 $select = implode(', ', $entitySingleSelectClauses);
718 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
719 foreach ($singleFieldTablesWithEntityData as $table) {
720 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
726 WHERE first.entity_id = $entityID
728 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
732 * Build the group tree for Custom fields which are 'is_multiple'
734 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
736 * @param array $groupTree
737 * (reference) group tree array which is being built.
738 * @param int $entityID
739 * Id of entity for whom the tree is being build up.
740 * @param array $entityMultipleSelectClauses
741 * Array of select clauses relevant to the entity.
742 * @param array $multipleFieldTablesWithEntityData
743 * Array of tables in which this entity has data.
744 * @param string|int $singleRecord
745 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
747 public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
748 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
749 $select = implode(',', $selectClauses);
753 WHERE entity_id = $entityID
756 $offset = $singleRecord - 1;
757 $query .= " LIMIT {$offset}, 1";
759 self
::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
764 * Build the tree entity data - starting from a query retrieving the custom fields build the group
765 * tree data for the relevant entity (entity is included in the query).
767 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
769 * @param array $groupTree
770 * (reference) group tree array which is being built.
771 * @param string $query
772 * @param array $includedTables
773 * Tables to include - required because the function (for historical reasons).
774 * iterates through the group tree
775 * @param string|int $singleRecord
776 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
778 public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
779 $dao = CRM_Core_DAO
::executeQuery($query);
780 while ($dao->fetch()) {
781 foreach ($groupTree as $groupID => $group) {
782 if ($groupID === 'info') {
785 $table = $groupTree[$groupID]['table_name'];
786 //working from the groupTree instead of the table list means we have to iterate & exclude.
787 // this could possibly be re-written as other parts of the function have been refactored
788 // for now we just check if the given table is to be included in this function
789 if (!in_array($table, $includedTables)) {
792 foreach ($group['fields'] as $fieldID => $dontCare) {
793 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
800 * Build the entity-specific custom data into the group tree on a per-field basis
803 * Object representing the custom field to be populated into the groupTree.
804 * @param array $groupTree
805 * (reference) the group tree being build.
806 * @param string $table
808 * @param int $groupID
810 * @param int $fieldID
812 * @param string|int $singleRecord
813 * holds 'new' or id if loading view/edit/copy for a single record.
815 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
816 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
817 $idName = "{$table}_id";
818 $fieldName = "{$table}_{$column}";
819 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
820 if ($dataType == 'File') {
821 if (isset($dao->$fieldName)) {
822 $config = CRM_Core_Config
::singleton();
823 $fileDAO = new CRM_Core_DAO_File();
824 $fileDAO->id
= $dao->$fieldName;
826 if ($fileDAO->find(TRUE)) {
827 $entityIDName = "{$table}_entity_id";
828 $fileHash = CRM_Core_BAO_File
::generateFileHash($dao->$entityIDName, $fileDAO->id
);
829 $customValue['id'] = $dao->$idName;
830 $customValue['data'] = $fileDAO->uri
;
831 $customValue['fid'] = $fileDAO->id
;
832 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
833 $customValue['displayURL'] = NULL;
834 $deleteExtra = ts('Are you sure you want to delete attached file.');
836 CRM_Core_Action
::DELETE
=> [
837 'name' => ts('Delete Attached File'),
838 'url' => 'civicrm/file',
839 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
840 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
841 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
844 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
845 CRM_Core_Action
::DELETE
,
847 'id' => $fileDAO->id
,
848 'eid' => $dao->$entityIDName,
854 'file.manage.delete',
858 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
859 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
860 if ($fileDAO->mime_type
== "image/jpeg" ||
861 $fileDAO->mime_type
== "image/pjpeg" ||
862 $fileDAO->mime_type
== "image/gif" ||
863 $fileDAO->mime_type
== "image/x-png" ||
864 $fileDAO->mime_type
== "image/png"
866 $customValue['displayURL'] = $customValue['fileURL'];
867 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
872 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
874 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId);
875 if ($path && file_exists($path)) {
876 list($imageWidth, $imageHeight) = getimagesize($path);
877 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
878 $customValue['imageThumbWidth'] = $imageThumbWidth;
879 $customValue['imageThumbHeight'] = $imageThumbHeight;
886 'id' => $dao->$idName,
893 'id' => $dao->$idName,
894 'data' => $dao->$fieldName,
898 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
899 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
901 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
902 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
904 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
905 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
908 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
913 * Get the group title.
921 public static function getTitle($id) {
922 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
926 * Get custom group details for a group.
928 * An array containing custom group details (including their custom field) is returned.
930 * @param int $groupId
931 * Group id whose details are needed.
932 * @param bool $searchable
933 * Is this field searchable.
934 * @param array $extends
935 * Which table does it extend if any.
937 * @param bool $inSelector
940 * array consisting of all group and field details
942 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
946 // using tableData to build the queryString
948 'civicrm_custom_field' => [
972 'civicrm_custom_group' => [
979 'collapse_adv_display',
981 'extends_entity_column_value',
989 foreach ($tableData as $tableName => $tableColumn) {
990 foreach ($tableColumn as $columnName) {
991 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
994 $select = 'SELECT ' . implode(', ', $s);
996 // from, where, order by
997 $from = " FROM civicrm_custom_field, civicrm_custom_group";
998 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
999 AND civicrm_custom_group.is_active = 1
1000 AND civicrm_custom_field.is_active = 1 ";
1002 $params[1] = [$groupId, 'Integer'];
1003 $where .= " AND civicrm_custom_group.id = %1";
1007 $where .= " AND civicrm_custom_field.is_searchable = 1";
1011 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1016 foreach ($extends as $e) {
1017 $clause[] = "civicrm_custom_group.extends = '$e'";
1019 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1021 //include case activities customdata if case is enabled
1022 if (in_array('Activity', $extends)) {
1023 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1024 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1025 $params[2] = [CRM_Core_DAO
::VALUE_SEPARATOR
, 'String'];
1029 // ensure that the user has access to these custom groups
1031 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1032 'civicrm_custom_group.'
1035 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1037 // final query string
1038 $queryString = $select . $from . $where . $orderBy;
1041 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1044 while ($crmDAO->fetch()) {
1045 $groupId = $crmDAO->civicrm_custom_group_id
;
1046 $fieldId = $crmDAO->civicrm_custom_field_id
;
1048 // create an array for groups if it does not exist
1049 if (!array_key_exists($groupId, $groupTree)) {
1050 $groupTree[$groupId] = [];
1051 $groupTree[$groupId]['id'] = $groupId;
1053 foreach ($tableData['civicrm_custom_group'] as $v) {
1054 $fullField = "civicrm_custom_group_" . $v;
1056 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1060 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1063 $groupTree[$groupId]['fields'] = [];
1066 // add the fields now (note - the query row will always contain a field)
1067 $groupTree[$groupId]['fields'][$fieldId] = [];
1068 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1070 foreach ($tableData['civicrm_custom_field'] as $v) {
1071 $fullField = "civicrm_custom_field_" . $v;
1072 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1075 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1083 * @param $entityType
1085 * @param string $cidToken
1089 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1091 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1093 // get 'Tab' and 'Tab with table' groups
1094 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1095 $customGroupDAO->whereAdd("is_active = 1");
1097 // add whereAdd for entity type
1098 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1102 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1103 $customGroupDAO->whereAdd($permissionClause);
1106 $customGroupDAO->orderBy('weight');
1107 $customGroupDAO->find();
1109 // process each group with menu tab
1110 while ($customGroupDAO->fetch()) {
1112 $group['id'] = $customGroupDAO->id
;
1113 $group['path'] = $path;
1114 $group['title'] = "$customGroupDAO->title";
1115 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1116 $group['extra'] = ['gid' => $customGroupDAO->id
];
1117 $group['table_name'] = $customGroupDAO->table_name
;
1118 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1119 $group['icon'] = $customGroupDAO->icon
;
1127 * Get the table name for the entity type
1128 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1129 * tableName is 'civicrm_contact'
1131 * @param string $entityType
1132 * What entity are we extending here ?.
1137 * @see _apachesolr_civiAttachments_dereference_file_parent
1139 public static function getTableNameByEntityName($entityType) {
1140 switch ($entityType) {
1144 case 'Organization':
1145 return 'civicrm_contact';
1148 return CRM_Core_DAO_AllCoreTables
::getTableForEntityName($entityType);
1153 * Get a list of custom groups which extend a given entity type.
1154 * If there are custom-groups which only apply to certain subtypes,
1155 * those WILL be included.
1157 * @param string $entityType
1159 * @return CRM_Core_DAO_CustomGroup
1161 public static function getAllCustomGroupsByBaseEntity($entityType) {
1162 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1163 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1164 return $customGroupDAO;
1168 * Add the whereAdd clause for the DAO depending on the type of entity
1169 * the custom group is extending.
1171 * @param object $customGroupDAO
1172 * @param string $entityType
1173 * What entity are we extending here ?.
1175 * @param int $entityID
1176 * @param bool $allSubtypes
1178 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1179 $addSubtypeClause = FALSE;
1180 // This function isn't really accessible with user data but since the string
1181 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1183 $entityType = CRM_Core_DAO
::escapeString($entityType);
1185 switch ($entityType) {
1187 // if contact, get all related to contact
1188 $extendList = "'Contact','Individual','Household','Organization'";
1189 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1190 if (!$allSubtypes) {
1191 $addSubtypeClause = TRUE;
1197 case 'Organization':
1198 // is I/H/O then get I/H/O and contact
1199 $extendList = "'Contact','$entityType'";
1200 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1201 if (!$allSubtypes) {
1202 $addSubtypeClause = TRUE;
1207 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1211 if ($addSubtypeClause) {
1212 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1214 if (!empty($csType)) {
1215 $subtypeClause = [];
1216 foreach ($csType as $subtype) {
1217 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1218 CRM_Core_DAO
::VALUE_SEPARATOR
;
1219 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1221 $subtypeClause[] = "extends_entity_column_value IS NULL";
1222 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1226 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1232 * Delete the Custom Group.
1234 * @param CRM_Core_BAO_CustomGroup $group
1235 * Custom group object.
1236 * @param bool $force
1237 * whether to force the deletion, even if there are custom fields.
1240 * False if field exists for this group, true if group gets deleted.
1242 public static function deleteGroup($group, $force = FALSE) {
1244 //check whether this contain any custom fields
1245 $customField = new CRM_Core_DAO_CustomField();
1246 $customField->custom_group_id
= $group->id
;
1247 $customField->find();
1249 // return early if there are custom fields and we're not
1250 // forcing the delete, otherwise delete the fields one by one
1251 while ($customField->fetch()) {
1255 CRM_Core_BAO_CustomField
::deleteField($customField);
1258 // drop the table associated with this custom group
1259 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1261 //delete custom group
1264 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1270 * Delete a record from supplied params.
1271 * API3 calls deleteGroup() which removes the related civicrm_value_X table.
1272 * This function does the same for API4.
1274 * @param array $record
1276 * @return CRM_Core_DAO
1277 * @throws CRM_Core_Exception
1279 public static function deleteRecord(array $record) {
1280 $table = CRM_Core_DAO
::getFieldValue(__CLASS__
, $record['id'], 'table_name');
1281 $result = parent
::deleteRecord($record);
1282 CRM_Core_BAO_SchemaHandler
::dropTable($table);
1289 * @param array $groupTree
1290 * @param array $defaults
1291 * @param bool $viewMode
1292 * @param bool $inactiveNeeded
1293 * @param int $action
1295 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1296 foreach ($groupTree as $id => $group) {
1297 if (!isset($group['fields'])) {
1300 foreach ($group['fields'] as $field) {
1301 if (isset($field['element_value'])) {
1302 $value = $field['element_value'];
1304 elseif (isset($field['default_value']) &&
1305 ($action != CRM_Core_Action
::UPDATE ||
1307 !array_key_exists('element_value', $field)
1310 $value = $viewMode ?
NULL : $field['default_value'];
1316 if (empty($field['element_name'])) {
1320 $elementName = $field['element_name'];
1321 $serialize = CRM_Core_BAO_CustomField
::isSerialized($field);
1324 if ($field['data_type'] != 'Country' && $field['data_type'] != 'StateProvince' && $field['data_type'] != 'ContactReference') {
1325 $defaults[$elementName] = [];
1326 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1328 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1329 if (isset($value)) {
1330 foreach ($customOption as $customValue => $customLabel) {
1331 if (in_array($customValue, $checkedData)) {
1332 if ($field['html_type'] == 'CheckBox') {
1333 $defaults[$elementName][$customValue] = 1;
1336 $defaults[$elementName][$customValue] = $customValue;
1340 $defaults[$elementName][$customValue] = 0;
1346 if (isset($field['customValue']['data'])) {
1347 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1348 foreach ($customOption as $val) {
1349 if (in_array($val['value'], $checkedData)) {
1350 if ($field['html_type'] == 'CheckBox') {
1351 $defaults[$elementName][$val['value']] = 1;
1354 $defaults[$elementName][$val['value']] = $val['value'];
1358 $defaults[$elementName][$val['value']] = 0;
1363 // Values may be "array strings" or actual arrays. Handle both.
1364 if (is_array($value) && count($value)) {
1365 CRM_Utils_Array
::formatArrayKeys($value);
1366 $checkedValue = $value;
1369 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1371 foreach ($customOption as $val) {
1372 if (in_array($val['value'], $checkedValue)) {
1373 if ($field['html_type'] == 'CheckBox') {
1374 $defaults[$elementName][$val['value']] = 1;
1377 $defaults[$elementName][$val['value']] = $val['value'];
1385 if (isset($value)) {
1386 // Values may be "array strings" or actual arrays. Handle both.
1387 if (is_array($value) && count($value)) {
1388 CRM_Utils_Array
::formatArrayKeys($value);
1389 $checkedValue = $value;
1391 // Serialized values from db
1392 elseif ($value === '' ||
strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1393 $checkedValue = CRM_Utils_Array
::explodePadded($value);
1395 // Comma-separated values e.g. from a select2 widget during reload on form error
1397 $checkedValue = explode(',', $value);
1399 foreach ($checkedValue as $val) {
1401 $defaults[$elementName][$val] = $val;
1408 if ($field['data_type'] == 'Country') {
1410 $defaults[$elementName] = $value;
1413 $config = CRM_Core_Config
::singleton();
1414 $defaults[$elementName] = $config->defaultContactCountry
;
1418 if ($field['data_type'] == "Float") {
1419 $defaults[$elementName] = (float) $value;
1421 elseif ($field['data_type'] == 'Money' &&
1422 $field['html_type'] == 'Text'
1424 $defaults[$elementName] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($value);
1427 $defaults[$elementName] = $value;
1436 * Old function only called from one place...
1437 * @see CRM_Dedupe_Finder::formatParams
1439 * @param array $groupTree
1440 * @param array $params
1441 * @param bool $skipFile
1443 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1444 // Get the Custom form values and groupTree
1445 foreach ($groupTree as $groupID => $group) {
1446 if ($groupID === 'info') {
1449 foreach ($group['fields'] as $field) {
1450 $fieldId = $field['id'];
1451 $serialize = CRM_Core_BAO_CustomField
::isSerialized($field);
1453 // Reset all checkbox, radio and multiselect data
1454 if ($field['html_type'] == 'Radio' ||
$serialize) {
1455 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1459 foreach ($params as $key => $val) {
1460 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1461 $match[1] == $field['id']
1467 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1468 // field exists in db so populate value from "form".
1469 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
1472 // Serialize checkbox and multi-select data (using array keys for checkbox)
1474 $v = ($v && $field['html_type'] === 'Checkbox') ?
array_keys($v) : $v;
1475 $v = $v ? CRM_Utils_Array
::implodePadded($v) : NULL;
1478 switch ($field['html_type']) {
1481 $date = CRM_Utils_Date
::processDate($v);
1482 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1490 // store the file in d/b
1491 $entityId = explode('=', $groupTree['info']['where'][0]);
1492 $fileParams = ['upload_date' => date('YmdHis')];
1494 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1495 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1498 $fileParams['uri'] = $v['name'];
1499 $fileParams['mime_type'] = $v['type'];
1500 CRM_Core_BAO_File
::filePostProcess($v['name'],
1501 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1502 $groupTree[$groupID]['table_name'],
1507 'custom_' . $fieldId,
1513 'entity_table' => $groupTree[$groupID]['table_name'],
1514 'entity_id' => $entityId[1],
1517 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1522 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1526 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1534 * Generic function to build all the form elements for a specific group tree.
1536 * @param CRM_Core_Form $form
1538 * @param array $groupTree
1539 * The group tree object.
1540 * @param bool $inactiveNeeded
1541 * Return inactive custom groups.
1542 * @param string $prefix
1543 * Prefix for custom grouptree assigned to template.
1545 * @throws \CiviCRM_API3_Exception
1547 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1548 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1550 foreach ($groupTree as $id => $group) {
1551 foreach ($group['fields'] as $field) {
1552 $required = $field['is_required'] ??
NULL;
1554 if ($field['data_type'] == 'File') {
1555 if (!empty($field['element_value']['data'])) {
1560 $fieldId = $field['id'];
1561 $elementName = $field['element_name'];
1562 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1563 if ($form->getAction() == CRM_Core_Action
::VIEW
) {
1564 $form->getElement($elementName)->freeze();
1571 * Extract the get params from the url, validate and store it in session.
1573 * @param CRM_Core_Form $form
1575 * @param string $type
1576 * The type of custom group we are using.
1579 * @throws \CRM_Core_Exception
1580 * @throws \CiviCRM_API3_Exception
1582 public static function extractGetParams(&$form, $type) {
1587 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1596 foreach ($groupTree as $group) {
1597 if (!isset($group['fields'])) {
1600 foreach ($group['fields'] as $key => $field) {
1601 $fieldName = 'custom_' . $key;
1602 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1606 if (!in_array($field['html_type'], $htmlType) ||
1607 $field['data_type'] == 'Boolean'
1609 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1611 if (CRM_Core_BAO_CustomField
::isSerialized($field)) {
1612 $value = str_replace("|", ",", $value);
1613 $mulValues = explode(',', $value);
1614 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1616 foreach ($mulValues as $v1) {
1617 foreach ($customOption as $coID => $coValue) {
1618 if (strtolower(trim($coValue['label'])) ==
1619 strtolower(trim($v1))
1621 $val[$coValue['value']] = 1;
1633 elseif ($field['html_type'] === 'Select' ||
1634 ($field['html_type'] === 'Radio' &&
1635 $field['data_type'] !== 'Boolean'
1638 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1639 foreach ($customOption as $customID => $coValue) {
1640 if (strtolower(trim($coValue['label'])) ==
1641 strtolower(trim($value))
1643 $value = $coValue['value'];
1648 elseif ($field['data_type'] === 'Date') {
1649 $valid = CRM_Utils_Rule
::date($value);
1653 $customValue[$fieldName] = $value;
1659 return $customValue;
1663 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1664 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1666 * @param int $customFieldId
1668 * @param array $removeCustomFieldTypes
1669 * Remove custom fields of a type eg: array("Individual") ;.
1672 * false if it matches else true
1674 * @throws \CRM_Core_Exception
1676 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1677 $query = 'SELECT cg.extends as extends
1678 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1679 WHERE cg.id = cf.custom_group_id
1681 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1683 $extends = CRM_Core_DAO
::singleValueQuery($query);
1685 if (in_array($extends, $removeCustomFieldTypes)) {
1697 public static function mapTableName($table) {
1702 case 'Organization':
1703 return 'civicrm_contact';
1706 return 'civicrm_activity';
1709 return 'civicrm_group';
1711 case 'Contribution':
1712 return 'civicrm_contribution';
1714 case 'ContributionRecur':
1715 return 'civicrm_contribution_recur';
1717 case 'Relationship':
1718 return 'civicrm_relationship';
1721 return 'civicrm_event';
1724 return 'civicrm_membership';
1727 case 'ParticipantRole':
1728 case 'ParticipantEventName':
1729 case 'ParticipantEventType':
1730 return 'civicrm_participant';
1733 return 'civicrm_grant';
1736 return 'civicrm_pledge';
1739 return 'civicrm_address';
1742 return 'civicrm_campaign';
1746 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1747 $qParams = [1 => [$table, 'String']];
1748 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1751 return 'civicrm_contact';
1754 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1755 if (array_key_exists($table, $extendObjs)) {
1756 return $extendObjs[$table];
1758 throw new CRM_Core_Exception('Unknown error');
1766 * @throws \Exception
1768 public static function createTable($group) {
1770 'name' => $group->table_name
,
1771 'is_multiple' => $group->is_multiple ?
1 : 0,
1772 'extends_name' => self
::mapTableName($group->extends),
1775 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1777 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1781 * Function returns formatted groupTree, so that form can be easily built in template
1783 * @param array $groupTree
1784 * @param int $groupCount
1785 * Group count by default 1, but can vary for multiple value custom data.
1786 * @param \CRM_Core_Form $form
1789 * @throws \CRM_Core_Exception
1791 public static function formatGroupTree($groupTree, $groupCount = 1, &$form = NULL) {
1792 $formattedGroupTree = [];
1793 $uploadNames = $formValues = [];
1795 // retrieve qf key from url
1796 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1798 // fetch submitted custom field values later use to set as a default values
1800 $submittedValues = Civi
::cache('customData')->get($qfKey);
1803 foreach ($groupTree as $key => $value) {
1804 if ($key === 'info') {
1808 // add group information
1809 $formattedGroupTree[$key]['name'] = $value['name'] ??
NULL;
1810 $formattedGroupTree[$key]['title'] = $value['title'] ??
NULL;
1811 $formattedGroupTree[$key]['help_pre'] = $value['help_pre'] ??
NULL;
1812 $formattedGroupTree[$key]['help_post'] = $value['help_post'] ??
NULL;
1813 $formattedGroupTree[$key]['collapse_display'] = $value['collapse_display'] ??
NULL;
1814 $formattedGroupTree[$key]['collapse_adv_display'] = $value['collapse_adv_display'] ??
NULL;
1815 $formattedGroupTree[$key]['style'] = $value['style'] ??
NULL;
1817 // this params needed of bulding multiple values
1818 $formattedGroupTree[$key]['is_multiple'] = $value['is_multiple'] ??
NULL;
1819 $formattedGroupTree[$key]['extends'] = $value['extends'] ??
NULL;
1820 $formattedGroupTree[$key]['extends_entity_column_id'] = $value['extends_entity_column_id'] ??
NULL;
1821 $formattedGroupTree[$key]['extends_entity_column_value'] = $value['extends_entity_column_value'] ??
NULL;
1822 $formattedGroupTree[$key]['subtype'] = $value['subtype'] ??
NULL;
1823 $formattedGroupTree[$key]['max_multiple'] = $value['max_multiple'] ??
NULL;
1825 // Properties that might have been filtered out but which
1826 // should be present to avoid smarty e-notices.
1827 $expectedProperties = ['options_per_line', 'help_pre', 'help_post'];
1828 // add field information
1829 foreach ($value['fields'] as $k => $properties) {
1830 $properties = array_merge(array_fill_keys($expectedProperties, 'NULL'), $properties);
1831 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1832 if (isset($properties['customValue']) &&
1833 !CRM_Utils_System
::isNull($properties['customValue']) &&
1834 !isset($properties['element_value'])
1836 if (isset($properties['customValue'][$groupCount])) {
1837 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1838 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1839 if ($properties['data_type'] === 'File') {
1840 $properties['element_value'] = $properties['customValue'][$groupCount];
1841 $uploadNames[] = $properties['element_name'];
1844 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1848 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1849 $formValues[$properties['element_name']] = $value;
1851 elseif (isset($submittedValues[$properties['element_name']])) {
1852 $properties['element_value'] = $submittedValues[$properties['element_name']];
1854 unset($properties['customValue']);
1855 $formattedGroupTree[$key]['fields'][$k] = $properties;
1860 if (count($formValues)) {
1861 $qf = $form->get('qfKey');
1862 $form->assign('qfKey', $qf);
1863 Civi
::cache('customData')->set($qf, $formValues);
1866 // hack for field type File
1867 $formUploadNames = $form->get('uploadNames');
1868 if (is_array($formUploadNames)) {
1869 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1872 $form->set('uploadNames', $uploadNames);
1875 return $formattedGroupTree;
1879 * Build custom data view.
1881 * @param CRM_Core_Form|CRM_Core_Page $form
1883 * @param array $groupTree
1884 * @param bool $returnCount
1885 * True if customValue count needs to be returned.
1887 * @param null $prefix
1888 * @param int $customValueId
1889 * @param int $entityId
1890 * @param bool $checkEditPermission
1893 * @throws \CRM_Core_Exception
1895 public static function buildCustomDataView(&$form, $groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL, $checkEditPermission = FALSE) {
1896 // Filter out pesky extra info
1897 unset($groupTree['info']);
1901 $editableGroups = [];
1902 if ($checkEditPermission) {
1903 $editableGroups = \CRM_Core_Permission
::customGroup(CRM_Core_Permission
::EDIT
);
1906 foreach ($groupTree as $key => $group) {
1908 foreach ($group['fields'] as $k => $properties) {
1909 $groupID = $group['id'];
1910 if (!empty($properties['customValue'])) {
1911 foreach ($properties['customValue'] as $values) {
1912 if (!empty($customValueId) && $customValueId != $values['id']) {
1915 $details[$groupID][$values['id']]['title'] = $group['title'] ??
NULL;
1916 $details[$groupID][$values['id']]['name'] = $group['name'] ??
NULL;
1917 $details[$groupID][$values['id']]['help_pre'] = $group['help_pre'] ??
NULL;
1918 $details[$groupID][$values['id']]['help_post'] = $group['help_post'] ??
NULL;
1919 $details[$groupID][$values['id']]['collapse_display'] = $group['collapse_display'] ??
NULL;
1920 $details[$groupID][$values['id']]['collapse_adv_display'] = $group['collapse_adv_display'] ??
NULL;
1921 $details[$groupID][$values['id']]['style'] = $group['style'] ??
NULL;
1922 $details[$groupID][$values['id']]['fields'][$k] = [
1923 'field_title' => $properties['label'] ??
NULL,
1924 'field_type' => $properties['html_type'] ??
NULL,
1925 'field_data_type' => $properties['data_type'] ??
NULL,
1926 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1927 'options_per_line' => $properties['options_per_line'] ??
NULL,
1929 // editable = whether this set contains any non-read-only fields
1930 if (!isset($details[$groupID][$values['id']]['editable'])) {
1931 $details[$groupID][$values['id']]['editable'] = FALSE;
1933 if (empty($properties['is_view']) && in_array($key, $editableGroups)) {
1934 $details[$groupID][$values['id']]['editable'] = TRUE;
1936 // also return contact reference contact id if user has view all or edit all contacts perm
1937 if ($details[$groupID][$values['id']]['fields'][$k]['field_data_type'] === 'ContactReference'
1938 && CRM_Core_Permission
::check([['view all contacts', 'edit all contacts']])
1940 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'] = [];
1941 $path = CRM_Contact_DAO_Contact
::getEntityPaths()['view'];
1942 foreach (CRM_Utils_Array
::explodePadded($values['data'] ??
[]) as $contactId) {
1943 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'display_name');
1945 $url = CRM_Utils_System
::url(str_replace('[id]', $contactId, $path));
1946 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'][] = '<a href="' . $url . '" title="' . htmlspecialchars(ts('View Contact')) . '">' .
1947 $displayName . '</a>';
1954 $details[$groupID][0]['title'] = $group['title'] ??
NULL;
1955 $details[$groupID][0]['name'] = $group['name'] ??
NULL;
1956 $details[$groupID][0]['help_pre'] = $group['help_pre'] ??
NULL;
1957 $details[$groupID][0]['help_post'] = $group['help_post'] ??
NULL;
1958 $details[$groupID][0]['collapse_display'] = $group['collapse_display'] ??
NULL;
1959 $details[$groupID][0]['collapse_adv_display'] = $group['collapse_adv_display'] ??
NULL;
1960 $details[$groupID][0]['style'] = $group['style'] ??
NULL;
1961 $details[$groupID][0]['fields'][$k] = ['field_title' => $properties['label'] ??
NULL];
1967 // return a single value count if group id is passed to function
1968 // else return a groupId and count mapped array
1970 return count($details[$gID]);
1974 foreach ($details as $key => $value) {
1975 $countValue[$key] = count($details[$key]);
1981 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1987 * Get the custom group titles by custom field ids.
1989 * @param array $fieldIds
1990 * Array of custom field ids.
1992 * @return array|NULL
1993 * array consisting of groups and fields labels with ids.
1995 public static function getGroupTitles($fieldIds) {
1996 if (!is_array($fieldIds) && empty($fieldIds)) {
2001 $fIds = "(" . implode(',', $fieldIds) . ")";
2004 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2005 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2006 FROM civicrm_custom_group, civicrm_custom_field
2007 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2008 AND civicrm_custom_field.id IN {$fIds}";
2010 $dao = CRM_Core_DAO
::executeQuery($query);
2011 while ($dao->fetch()) {
2012 $groupLabels[$dao->fieldID
] = [
2013 'fieldID' => $dao->fieldID
,
2014 'fieldLabel' => $dao->fieldLabel
,
2015 'groupID' => $dao->groupID
,
2016 'groupTitle' => $dao->groupTitle
,
2020 return $groupLabels;
2023 public static function dropAllTables() {
2024 $query = "SELECT table_name FROM civicrm_custom_group";
2025 $dao = CRM_Core_DAO
::executeQuery($query);
2027 while ($dao->fetch()) {
2028 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2029 CRM_Core_DAO
::executeQuery($query);
2034 * Check whether custom group is empty or not.
2040 * true if empty otherwise false.
2042 public static function isGroupEmpty($gID) {
2047 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2052 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2053 $value = CRM_Core_DAO
::singleValueQuery($query);
2055 if (empty($value)) {
2063 * Get the list of types for objects that a custom group extends to.
2065 * @param array $types
2066 * Var which should have the list appended.
2070 * @throws \Exception
2072 public static function getExtendedObjectTypes(&$types = []) {
2073 static $flag = FALSE, $objTypes = [];
2077 CRM_Core_OptionValue
::getValues(['name' => 'cg_extend_objects'], $extendObjs, 'weight', TRUE);
2079 foreach ($extendObjs as $ovId => $ovValues) {
2080 if ($ovValues['description']) {
2081 // description is expected to be a callback func to subtypes
2082 list($callback, $args) = explode(';', trim($ovValues['description']));
2088 if (!is_array($args)) {
2089 throw new CRM_Core_Exception('Arg is not of type array');
2092 list($className) = explode('::', $callback);
2093 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
2095 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2101 $types = array_merge($types, $objTypes);
2106 * @param int $customGroupId
2107 * @param int $entityId
2111 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2112 // check whether the group is multiple
2113 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2114 $isMultiple = (bool) $isMultiple;
2115 $hasReachedMax = FALSE;
2117 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2119 if (!$maxMultiple) {
2120 $hasReachedMax = FALSE;
2123 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2124 // count the number of entries for a entity
2125 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2126 $params = [1 => [$entityId, 'Integer']];
2127 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2129 if ($count >= $maxMultiple) {
2130 $hasReachedMax = TRUE;
2134 return $hasReachedMax;
2140 public static function getMultipleFieldGroup() {
2141 $multipleGroup = [];
2142 $dao = new CRM_Core_DAO_CustomGroup();
2143 $dao->is_multiple
= 1;
2144 $dao->is_active
= 1;
2146 while ($dao->fetch()) {
2147 $multipleGroup[$dao->id
] = $dao->title
;
2149 return $multipleGroup;
2153 * Build the metadata tree for the custom group.
2155 * @param string $entityType
2156 * @param array $toReturn
2157 * @param array $subTypes
2158 * @param string $queryString
2159 * @param array $params
2160 * @param string $subType
2163 * @throws \CRM_Core_Exception
2165 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2166 $groupTree = $multipleFieldGroups = [];
2167 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
2168 $customValueTables = [];
2171 while ($crmDAO->fetch()) {
2173 $groupID = $crmDAO->civicrm_custom_group_id
;
2174 $fieldId = $crmDAO->civicrm_custom_field_id
;
2175 if ($crmDAO->civicrm_custom_group_is_multiple
) {
2176 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
2178 // create an array for groups if it does not exist
2179 if (!array_key_exists($groupID, $groupTree)) {
2180 $groupTree[$groupID] = [];
2181 $groupTree[$groupID]['id'] = $groupID;
2183 // populate the group information
2184 foreach ($toReturn['custom_group'] as $fieldName) {
2185 $fullFieldName = "civicrm_custom_group_$fieldName";
2186 if ($fieldName == 'id' ||
2187 is_null($crmDAO->$fullFieldName)
2192 // This is an old bit of code - per the CRM number & probably does not work reliably if
2193 // that one contact sub-type exists.
2194 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2195 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
2197 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2199 $groupTree[$groupID]['fields'] = [];
2201 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = [];
2204 // add the fields now (note - the query row will always contain a field)
2205 // we only reset this once, since multiple values come is as multiple rows
2206 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2207 $groupTree[$groupID]['fields'][$fieldId] = [];
2210 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
2211 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2212 // populate information for a custom field
2213 foreach ($toReturn['custom_field'] as $fieldName) {
2214 $fullFieldName = "civicrm_custom_field_$fieldName";
2215 if ($fieldName == 'id' ||
2216 is_null($crmDAO->$fullFieldName)
2220 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2224 if (!empty($customValueTables)) {
2225 $groupTree['info'] = ['tables' => $customValueTables];
2227 return [$multipleFieldGroups, $groupTree];
2230 public static function getSubTypes(): array {
2232 $activityType = CRM_Core_PseudoConstant
::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
2234 $eventType = CRM_Core_OptionGroup
::values('event_type');
2235 $grantType = CRM_Core_OptionGroup
::values('grant_type');
2236 $campaignTypes = CRM_Campaign_PseudoConstant
::campaignType();
2237 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypes(FALSE);
2238 $participantRole = CRM_Core_OptionGroup
::values('participant_role');
2240 asort($activityType);
2243 asort($membershipType);
2244 asort($participantRole);
2246 $sel2['Event'] = $eventType;
2247 $sel2['Grant'] = $grantType;
2248 $sel2['Activity'] = $activityType;
2249 $sel2['Campaign'] = $campaignTypes;
2250 $sel2['Membership'] = $membershipType;
2251 $sel2['ParticipantRole'] = $participantRole;
2252 $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
2253 $sel2['ParticipantEventType'] = $eventType;
2254 $sel2['Contribution'] = CRM_Contribute_PseudoConstant
::financialType();
2255 $sel2['Relationship'] = CRM_Custom_Form_Group
::getRelationshipTypes();
2257 $sel2['Individual'] = CRM_Contact_BAO_ContactType
::subTypePairs('Individual', FALSE, NULL);
2258 $sel2['Household'] = CRM_Contact_BAO_ContactType
::subTypePairs('Household', FALSE, NULL);
2259 $sel2['Organization'] = CRM_Contact_BAO_ContactType
::subTypePairs('Organization', FALSE, NULL);
2261 CRM_Core_BAO_CustomGroup
::getExtendedObjectTypes($sel2);
2266 * Get the munged entity.
2268 * This is the entity eg. Relationship or the name of the sub entity
2269 * e.g ParticipantRole.
2271 * @param string $extends
2272 * @param int|null $extendsEntityColumn
2276 protected static function getMungedEntity($extends, $extendsEntityColumn = NULL) {
2277 if (!$extendsEntityColumn ||
$extendsEntityColumn === 'null') {
2280 return CRM_Core_OptionGroup
::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name')[$extendsEntityColumn];
2284 * @param int $groupId
2285 * @param int $operation
2286 * @param int|null $userId
2288 public static function checkGroupAccess($groupId, $operation = CRM_Core_Permission
::EDIT
, $userId = NULL): bool {
2289 $allowedGroups = CRM_Core_Permission
::customGroup($operation, FALSE, $userId);
2290 return in_array($groupId, $allowedGroups);