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 = CRM_Utils_Array
::value(0, $extends);
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 = CRM_Utils_Array
::value(1, $extends);
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',
110 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
111 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
112 if ($is_public_version) {
113 $fields[] = 'is_public';
115 foreach ($fields as $field) {
116 if (isset($params[$field])) {
117 $group->$field = $params[$field];
120 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
121 $params['max_multiple'] >= '0'
122 ) ?
$params['max_multiple'] : 'null' : 'null';
124 $tableName = $tableNameNeedingIndexUpdate = NULL;
125 if (isset($params['id'])) {
126 $group->id
= $params['id'];
128 if (isset($params['is_multiple'])) {
129 // check whether custom group was changed from single-valued to multiple-valued
130 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
135 // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
136 $paramsIsMultiple = empty($params['is_multiple']) ?
0 : 1;
137 if ($paramsIsMultiple != $isMultiple) {
138 $tableNameNeedingIndexUpdate = CRM_Core_DAO
::getFieldValue(
139 'CRM_Core_DAO_CustomGroup',
147 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
148 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
150 // we do this only once, so name never changes
151 if (isset($params['name'])) {
152 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
155 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
158 if (isset($params['table_name'])) {
159 $tableName = $params['table_name'];
161 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
162 // Bad idea. Prevent group creation because it might lead to a broken configuration.
163 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", ['1' => $tableName]));
168 if (array_key_exists('is_reserved', $params)) {
169 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
171 $op = isset($params['id']) ?
'edit' : 'create';
172 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
174 // enclose the below in a transaction
175 $transaction = new CRM_Core_Transaction();
178 if (!isset($params['id'])) {
179 if (!isset($params['table_name'])) {
180 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 13));
181 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
183 $group->table_name
= $tableName;
184 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
190 // now create the table associated with this group
191 self
::createTable($group);
193 elseif ($tableNameNeedingIndexUpdate) {
194 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array
::value('is_multiple', $params));
197 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
198 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
202 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($extendsEntity));
204 $transaction->commit();
207 CRM_Utils_System
::flushCache();
210 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
213 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
220 * Fetch object based on array of properties.
222 * @param array $params
223 * (reference ) an assoc array of name/value pairs.
224 * @param array $defaults
225 * (reference ) an assoc array to hold the flattened values.
227 * @return CRM_Core_DAO_CustomGroup
229 public static function retrieve(&$params, &$defaults) {
230 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
234 * Update the is_active flag in the db.
237 * Id of the database record.
238 * @param bool $is_active
239 * Value we want to set the is_active field.
242 * true if we found and updated the object, else false
244 public static function setIsActive($id, $is_active) {
246 Civi
::cache('fields')->flush();
247 // reset ACL and system caches.
248 CRM_Core_BAO_Cache
::resetCaches();
251 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
254 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
258 * Determine if given entity (sub)type has any custom groups
260 * @param string $extends
261 * E.g. "Individual", "Activity".
262 * @param int $columnId
263 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
264 * @param string $columnValue
265 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
269 public static function hasCustomGroup($extends, $columnId, $columnValue) {
270 $dao = new CRM_Core_DAO_CustomGroup();
271 $dao->extends = $extends;
272 $dao->extends_entity_column_id
= $columnId;
273 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
274 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
275 //$dao->extends_entity_column_value = $columnValue;
276 return $dao->find() ?
TRUE : FALSE;
280 * Determine if there are any CustomGroups for the given $activityTypeId.
281 * If none found, create one.
283 * @param int $activityTypeId
286 * TRUE if a group is found or created; FALSE on error
288 public static function autoCreateByActivityType($activityTypeId) {
289 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
293 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
296 'extends' => 'Activity',
297 'extends_entity_column_id' => NULL,
298 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded([$activityTypeId]),
299 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
303 $result = civicrm_api('CustomGroup', 'create', $params);
304 return !$result['is_error'];
308 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
309 * This may also include entity specific data values.
311 * An array containing all custom groups and their custom fields is returned.
313 * @param string $entityType
314 * Of the contact whose contact type is needed.
315 * @param array $toReturn
316 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
317 * @param int $entityID
318 * @param int $groupID
319 * @param array $subTypes
320 * @param string $subName
321 * @param bool $fromCache
322 * @param bool $onlySubType
323 * Only return specified subtype or return specified subtype + unrestricted fields.
324 * @param bool $returnAll
325 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
326 * api - through which it is properly tested - so can be refactored with some comfort.)
328 * @param bool $checkPermission
329 * @param string|int $singleRecord
330 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
331 * @param bool $showPublicOnly
334 * Custom field 'tree'.
336 * The returned array is keyed by group id and has the custom group table fields
337 * and a subkey 'fields' holding the specific custom fields.
338 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
339 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
341 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
342 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
343 * With caching the performance impact would be small & the function would be cleaner
345 * @throws \CRM_Core_Exception
347 public static function getTree(
357 $checkPermission = TRUE,
358 $singleRecord = NULL,
359 $showPublicOnly = FALSE
362 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
364 if (!is_array($subTypes)) {
365 if (empty($subTypes)) {
369 if (stristr($subTypes, ',')) {
370 $subTypes = explode(',', $subTypes);
373 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
380 // legacy hardcoded list of data to return
414 'extends_entity_column_id',
415 'extends_entity_column_value',
419 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
420 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
421 if ($is_public_version) {
422 $tableData['custom_group'][] = 'is_public';
424 if (!$toReturn ||
!is_array($toReturn)) {
425 $toReturn = $tableData;
428 // Supply defaults and remove unknown array keys
429 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
430 // Merge in required fields that we must have
431 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
432 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
433 // Validate return fields
434 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
435 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
440 foreach ($toReturn as $tableName => $tableColumn) {
441 foreach ($tableColumn as $columnName) {
442 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
445 $strSelect = "SELECT " . implode(', ', $select);
447 // from, where, order by
449 FROM civicrm_custom_group
450 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
453 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
454 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
455 $entityType == 'Household'
457 $in = "'$entityType', 'Contact'";
459 elseif (strpos($entityType, "'") !== FALSE) {
460 // this allows the calling function to send in multiple entity types
465 $in = "'$entityType'";
471 if (!empty($subTypes)) {
472 foreach ($subTypes as $key => $subType) {
473 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
475 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
477 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
481 WHERE civicrm_custom_group.is_active = 1
482 AND civicrm_custom_field.is_active = 1
483 AND civicrm_custom_group.extends IN ($in)
487 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
488 $params[$sqlParamKey] = [$subName, 'String'];
489 $sqlParamKey = $sqlParamKey +
1;
494 WHERE civicrm_custom_group.is_active = 1
495 AND civicrm_custom_field.is_active = 1
496 AND civicrm_custom_group.extends IN ($in)
499 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
504 // since we want a specific group id we add it to the where clause
505 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
506 $params[$sqlParamKey] = [$groupID, 'Integer'];
509 // since groupID is false we need to show all Inline groups
510 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
512 if ($checkPermission) {
513 // ensure that the user has access to these custom groups
514 $strWhere .= " AND " .
515 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
516 'civicrm_custom_group.'
520 if ($showPublicOnly && $is_public_version) {
521 $strWhere .= "AND civicrm_custom_group.is_public = 1";
525 ORDER BY civicrm_custom_group.weight,
526 civicrm_custom_group.title,
527 civicrm_custom_field.weight,
528 civicrm_custom_field.label
531 // final query string
532 $queryString = "$strSelect $strFrom $strWhere $orderBy";
534 // lets see if we can retrieve the groupTree from cache
535 $cacheString = $queryString;
537 $cacheString .= "_{$groupID}";
540 $cacheString .= "_Inline";
543 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
544 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
545 $cache = CRM_Utils_Cache
::singleton();
547 $groupTree = $cache->get($cacheKey);
548 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
551 if (empty($groupTree)) {
552 list($multipleFieldGroups, $groupTree) = self
::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType);
554 $cache->set($cacheKey, $groupTree);
555 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
557 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
558 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
559 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
560 $singleFieldTables = [];
561 // now that we have all the groups and fields, lets get the values
562 // since we need to know the table and field names
563 // add info to groupTree
565 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
566 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
568 $select = $from = $where = [];
569 $groupTree['info']['where'] = NULL;
571 foreach ($groupTree['info']['tables'] as $table => $fields) {
572 $groupTree['info']['from'][] = $table;
574 "{$table}.id as {$table}_id",
575 "{$table}.entity_id as {$table}_entity_id",
577 foreach ($fields as $column => $dontCare) {
578 $select[] = "{$table}.{$column} as {$table}_{$column}";
580 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
582 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
583 if (in_array($table, $multipleFieldGroups) &&
584 self
::customGroupDataExistsForEntity($entityID, $table)
586 $entityMultipleSelectClauses[$table] = $select;
589 $singleFieldTables[] = $table;
590 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
595 if ($entityID && !empty($singleFieldTables)) {
596 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
598 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
599 if (!empty($multipleFieldTablesWithEntityData)) {
600 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
608 * Clean and validate the filter before it is used in a db query.
610 * @param string $entityType
611 * @param string $subType
614 * @throws \CRM_Core_Exception
616 protected static function validateSubTypeByEntity($entityType, $subType) {
617 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
618 if (is_numeric($subType)) {
622 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
623 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
625 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
626 throw new CRM_Core_Exception('Invalid Entity Filter');
628 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
629 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
630 if (!array_key_exists($subType, $subTypes)) {
631 throw new CRM_Core_Exception('Invalid Filter');
637 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
638 * a WHERE condition for rows that include $value. Use whereListHas().
640 * @param string $column
641 * @param string $value
642 * @param string $delimiter
646 private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
648 $bareValue = trim($value, $delimiter);
649 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
650 return "($column LIKE \"$escapedValue\")";
654 * Check whether the custom group has any data for the given entity.
656 * @param int $entityID
657 * Id of entity for whom we are checking data for.
658 * @param string $table
659 * Table that we are checking.
661 * @param bool $getCount
664 * does this entity have data in this custom table
666 public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
670 WHERE entity_id = $entityID
672 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
674 return $recordExists;
676 return $recordExists ?
TRUE : FALSE;
680 * Build the group tree for Custom fields which are not 'is_multiple'
682 * The combination of all these fields in one query with a 'using' join was not working for
683 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
684 * mechanism as it seemed to be acceptable in this context
686 * @param array $groupTree
687 * (reference) group tree array which is being built.
688 * @param int $entityID
689 * Id of entity for whom the tree is being build up.
690 * @param array $entitySingleSelectClauses
691 * Array of select clauses relevant to the entity.
692 * @param array $singleFieldTablesWithEntityData
693 * Array of tables in which this entity has data.
695 public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
696 $select = implode(', ', $entitySingleSelectClauses);
697 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
698 foreach ($singleFieldTablesWithEntityData as $table) {
699 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
705 WHERE first.entity_id = $entityID
707 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
711 * Build the group tree for Custom fields which are 'is_multiple'
713 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
715 * @param array $groupTree
716 * (reference) group tree array which is being built.
717 * @param int $entityID
718 * Id of entity for whom the tree is being build up.
719 * @param array $entityMultipleSelectClauses
720 * Array of select clauses relevant to the entity.
721 * @param array $multipleFieldTablesWithEntityData
722 * Array of tables in which this entity has data.
723 * @param string|int $singleRecord
724 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
726 public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
727 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
728 $select = implode(',', $selectClauses);
732 WHERE entity_id = $entityID
735 $offset = $singleRecord - 1;
736 $query .= " LIMIT {$offset}, 1";
738 self
::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
743 * Build the tree entity data - starting from a query retrieving the custom fields build the group
744 * tree data for the relevant entity (entity is included in the query).
746 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
748 * @param array $groupTree
749 * (reference) group tree array which is being built.
750 * @param string $query
751 * @param array $includedTables
752 * Tables to include - required because the function (for historical reasons).
753 * iterates through the group tree
754 * @param string|int $singleRecord
755 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
757 public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
758 $dao = CRM_Core_DAO
::executeQuery($query);
759 while ($dao->fetch()) {
760 foreach ($groupTree as $groupID => $group) {
761 if ($groupID === 'info') {
764 $table = $groupTree[$groupID]['table_name'];
765 //working from the groupTree instead of the table list means we have to iterate & exclude.
766 // this could possibly be re-written as other parts of the function have been refactored
767 // for now we just check if the given table is to be included in this function
768 if (!in_array($table, $includedTables)) {
771 foreach ($group['fields'] as $fieldID => $dontCare) {
772 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
779 * Build the entity-specific custom data into the group tree on a per-field basis
782 * Object representing the custom field to be populated into the groupTree.
783 * @param array $groupTree
784 * (reference) the group tree being build.
785 * @param string $table
787 * @param int $groupID
789 * @param int $fieldID
791 * @param string|int $singleRecord
792 * holds 'new' or id if loading view/edit/copy for a single record.
794 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
795 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
796 $idName = "{$table}_id";
797 $fieldName = "{$table}_{$column}";
798 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
799 if ($dataType == 'File') {
800 if (isset($dao->$fieldName)) {
801 $config = CRM_Core_Config
::singleton();
802 $fileDAO = new CRM_Core_DAO_File();
803 $fileDAO->id
= $dao->$fieldName;
805 if ($fileDAO->find(TRUE)) {
806 $entityIDName = "{$table}_entity_id";
807 $fileHash = CRM_Core_BAO_File
::generateFileHash($dao->$entityIDName, $fileDAO->id
);
808 $customValue['id'] = $dao->$idName;
809 $customValue['data'] = $fileDAO->uri
;
810 $customValue['fid'] = $fileDAO->id
;
811 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
812 $customValue['displayURL'] = NULL;
813 $deleteExtra = ts('Are you sure you want to delete attached file.');
815 CRM_Core_Action
::DELETE
=> [
816 'name' => ts('Delete Attached File'),
817 'url' => 'civicrm/file',
818 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
819 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
820 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
823 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
824 CRM_Core_Action
::DELETE
,
826 'id' => $fileDAO->id
,
827 'eid' => $dao->$entityIDName,
833 'file.manage.delete',
837 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
838 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
839 if ($fileDAO->mime_type
== "image/jpeg" ||
840 $fileDAO->mime_type
== "image/pjpeg" ||
841 $fileDAO->mime_type
== "image/gif" ||
842 $fileDAO->mime_type
== "image/x-png" ||
843 $fileDAO->mime_type
== "image/png"
845 $customValue['displayURL'] = $customValue['fileURL'];
846 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
851 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
853 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId);
854 if ($path && file_exists($path)) {
855 list($imageWidth, $imageHeight) = getimagesize($path);
856 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
857 $customValue['imageThumbWidth'] = $imageThumbWidth;
858 $customValue['imageThumbHeight'] = $imageThumbHeight;
865 'id' => $dao->$idName,
872 'id' => $dao->$idName,
873 'data' => $dao->$fieldName,
877 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
878 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
880 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
881 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
883 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
884 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
887 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
892 * Get the group title.
900 public static function getTitle($id) {
901 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
905 * Get custom group details for a group.
907 * An array containing custom group details (including their custom field) is returned.
909 * @param int $groupId
910 * Group id whose details are needed.
911 * @param bool $searchable
912 * Is this field searchable.
913 * @param array $extends
914 * Which table does it extend if any.
916 * @param bool $inSelector
919 * array consisting of all group and field details
921 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
925 // using tableData to build the queryString
927 'civicrm_custom_field' => [
951 'civicrm_custom_group' => [
958 'collapse_adv_display',
960 'extends_entity_column_value',
968 foreach ($tableData as $tableName => $tableColumn) {
969 foreach ($tableColumn as $columnName) {
970 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
973 $select = 'SELECT ' . implode(', ', $s);
975 // from, where, order by
976 $from = " FROM civicrm_custom_field, civicrm_custom_group";
977 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
978 AND civicrm_custom_group.is_active = 1
979 AND civicrm_custom_field.is_active = 1 ";
981 $params[1] = [$groupId, 'Integer'];
982 $where .= " AND civicrm_custom_group.id = %1";
986 $where .= " AND civicrm_custom_field.is_searchable = 1";
990 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
995 foreach ($extends as $e) {
996 $clause[] = "civicrm_custom_group.extends = '$e'";
998 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1000 //include case activities customdata if case is enabled
1001 if (in_array('Activity', $extends)) {
1002 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1003 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1004 $params[2] = [CRM_Core_DAO
::VALUE_SEPARATOR
, 'String'];
1008 // ensure that the user has access to these custom groups
1010 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1011 'civicrm_custom_group.'
1014 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1016 // final query string
1017 $queryString = $select . $from . $where . $orderBy;
1020 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1023 while ($crmDAO->fetch()) {
1024 $groupId = $crmDAO->civicrm_custom_group_id
;
1025 $fieldId = $crmDAO->civicrm_custom_field_id
;
1027 // create an array for groups if it does not exist
1028 if (!array_key_exists($groupId, $groupTree)) {
1029 $groupTree[$groupId] = [];
1030 $groupTree[$groupId]['id'] = $groupId;
1032 foreach ($tableData['civicrm_custom_group'] as $v) {
1033 $fullField = "civicrm_custom_group_" . $v;
1035 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1039 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1042 $groupTree[$groupId]['fields'] = [];
1045 // add the fields now (note - the query row will always contain a field)
1046 $groupTree[$groupId]['fields'][$fieldId] = [];
1047 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1049 foreach ($tableData['civicrm_custom_field'] as $v) {
1050 $fullField = "civicrm_custom_field_" . $v;
1051 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1054 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1062 * @param $entityType
1064 * @param string $cidToken
1068 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1070 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1072 // get 'Tab' and 'Tab with table' groups
1073 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1074 $customGroupDAO->whereAdd("is_active = 1");
1076 // add whereAdd for entity type
1077 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1081 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1082 $customGroupDAO->whereAdd($permissionClause);
1085 $customGroupDAO->orderBy('weight');
1086 $customGroupDAO->find();
1088 // process each group with menu tab
1089 while ($customGroupDAO->fetch()) {
1091 $group['id'] = $customGroupDAO->id
;
1092 $group['path'] = $path;
1093 $group['title'] = "$customGroupDAO->title";
1094 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1095 $group['extra'] = ['gid' => $customGroupDAO->id
];
1096 $group['table_name'] = $customGroupDAO->table_name
;
1097 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1105 * Get the table name for the entity type
1106 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1107 * tableName is 'civicrm_contact'
1109 * @param string $entityType
1110 * What entity are we extending here ?.
1115 * @see _apachesolr_civiAttachments_dereference_file_parent
1117 public static function getTableNameByEntityName($entityType) {
1119 switch ($entityType) {
1123 case 'Organization':
1124 $tableName = 'civicrm_contact';
1127 case 'Contribution':
1128 $tableName = 'civicrm_contribution';
1132 $tableName = 'civicrm_group';
1135 // DRAFTING: Verify if we cannot make it pluggable
1138 $tableName = 'civicrm_activity';
1141 case 'Relationship':
1142 $tableName = 'civicrm_relationship';
1146 $tableName = 'civicrm_membership';
1150 $tableName = 'civicrm_participant';
1154 $tableName = 'civicrm_event';
1158 $tableName = 'civicrm_grant';
1161 // need to add cases for Location, Address
1168 * Get a list of custom groups which extend a given entity type.
1169 * If there are custom-groups which only apply to certain subtypes,
1170 * those WILL be included.
1172 * @param string $entityType
1174 * @return CRM_Core_DAO_CustomGroup
1176 public static function getAllCustomGroupsByBaseEntity($entityType) {
1177 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1178 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1179 return $customGroupDAO;
1183 * Add the whereAdd clause for the DAO depending on the type of entity
1184 * the custom group is extending.
1186 * @param object $customGroupDAO
1187 * @param string $entityType
1188 * What entity are we extending here ?.
1190 * @param int $entityID
1191 * @param bool $allSubtypes
1193 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1194 $addSubtypeClause = FALSE;
1195 // This function isn't really accessible with user data but since the string
1196 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1198 $entityType = CRM_Core_DAO
::escapeString($entityType);
1200 switch ($entityType) {
1202 // if contact, get all related to contact
1203 $extendList = "'Contact','Individual','Household','Organization'";
1204 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1205 if (!$allSubtypes) {
1206 $addSubtypeClause = TRUE;
1212 case 'Organization':
1213 // is I/H/O then get I/H/O and contact
1214 $extendList = "'Contact','$entityType'";
1215 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1216 if (!$allSubtypes) {
1217 $addSubtypeClause = TRUE;
1222 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1226 if ($addSubtypeClause) {
1227 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1229 if (!empty($csType)) {
1230 $subtypeClause = [];
1231 foreach ($csType as $subtype) {
1232 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1233 CRM_Core_DAO
::VALUE_SEPARATOR
;
1234 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1236 $subtypeClause[] = "extends_entity_column_value IS NULL";
1237 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1241 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1247 * Delete the Custom Group.
1249 * @param CRM_Core_BAO_CustomGroup $group
1250 * Custom group object.
1251 * @param bool $force
1252 * whether to force the deletion, even if there are custom fields.
1255 * False if field exists for this group, true if group gets deleted.
1257 public static function deleteGroup($group, $force = FALSE) {
1259 //check whether this contain any custom fields
1260 $customField = new CRM_Core_DAO_CustomField();
1261 $customField->custom_group_id
= $group->id
;
1262 $customField->find();
1264 // return early if there are custom fields and we're not
1265 // forcing the delete, otherwise delete the fields one by one
1266 while ($customField->fetch()) {
1270 CRM_Core_BAO_CustomField
::deleteField($customField);
1273 // drop the table associated with this custom group
1274 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1276 //delete custom group
1279 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1287 * @param array $groupTree
1288 * @param array $defaults
1289 * @param bool $viewMode
1290 * @param bool $inactiveNeeded
1291 * @param int $action
1293 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1294 foreach ($groupTree as $id => $group) {
1295 if (!isset($group['fields'])) {
1298 foreach ($group['fields'] as $field) {
1299 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1300 $value = $field['element_value'];
1302 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1303 ($action != CRM_Core_Action
::UPDATE ||
1305 !array_key_exists('element_value', $field)
1308 $value = $viewMode ?
NULL : $field['default_value'];
1314 if (empty($field['element_name'])) {
1318 $elementName = $field['element_name'];
1320 switch ($field['html_type']) {
1321 case 'Multi-Select':
1323 $defaults[$elementName] = [];
1324 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1326 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1327 if (isset($value)) {
1328 foreach ($customOption as $customValue => $customLabel) {
1329 if (in_array($customValue, $checkedData)) {
1330 if ($field['html_type'] == 'CheckBox') {
1331 $defaults[$elementName][$customValue] = 1;
1334 $defaults[$elementName][$customValue] = $customValue;
1338 $defaults[$elementName][$customValue] = 0;
1344 if (isset($field['customValue']['data'])) {
1345 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1346 foreach ($customOption as $val) {
1347 if (in_array($val['value'], $checkedData)) {
1348 if ($field['html_type'] == 'CheckBox') {
1349 $defaults[$elementName][$val['value']] = 1;
1352 $defaults[$elementName][$val['value']] = $val['value'];
1356 $defaults[$elementName][$val['value']] = 0;
1361 if (is_array($value) && count($value)) {
1362 CRM_Utils_Array
::formatArrayKeys($value);
1363 $checkedValue = $value;
1366 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1368 foreach ($customOption as $val) {
1369 if (in_array($val['value'], $checkedValue)) {
1370 if ($field['html_type'] == 'CheckBox') {
1371 $defaults[$elementName][$val['value']] = 1;
1374 $defaults[$elementName][$val['value']] = $val['value'];
1382 case 'Multi-Select Country':
1383 case 'Multi-Select State/Province':
1384 if (isset($value)) {
1385 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1386 foreach ($checkedValue as $val) {
1388 $defaults[$elementName][$val] = $val;
1394 case 'Select Country':
1396 $defaults[$elementName] = $value;
1399 $config = CRM_Core_Config
::singleton();
1400 $defaults[$elementName] = $config->defaultContactCountry
;
1405 if ($field['data_type'] == "Float") {
1406 $defaults[$elementName] = (float) $value;
1408 elseif ($field['data_type'] == 'Money' &&
1409 $field['html_type'] == 'Text'
1411 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1414 $defaults[$elementName] = $value;
1422 * PostProcess function.
1424 * @param array $groupTree
1425 * @param array $params
1426 * @param bool $skipFile
1428 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1429 // Get the Custom form values and groupTree
1430 // first reset all checkbox and radio data
1431 foreach ($groupTree as $groupID => $group) {
1432 if ($groupID === 'info') {
1435 foreach ($group['fields'] as $field) {
1436 $fieldId = $field['id'];
1438 //added Multi-Select option in the below if-statement
1439 if ($field['html_type'] == 'CheckBox' ||
1440 $field['html_type'] == 'Radio' ||
1441 $field['html_type'] == 'Multi-Select'
1443 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1447 foreach ($params as $key => $val) {
1448 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1449 $match[1] == $field['id']
1455 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1456 // field exists in db so populate value from "form".
1457 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
1460 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1462 // added for CheckBox
1465 $customValue = array_keys($v);
1466 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1467 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1468 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1471 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1475 case 'Multi-Select':
1477 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1478 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1479 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1482 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1487 $date = CRM_Utils_Date
::processDate($v);
1488 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1496 // store the file in d/b
1497 $entityId = explode('=', $groupTree['info']['where'][0]);
1498 $fileParams = ['upload_date' => date('YmdHis')];
1500 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1501 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1504 $fileParams['uri'] = $v['name'];
1505 $fileParams['mime_type'] = $v['type'];
1506 CRM_Core_BAO_File
::filePostProcess($v['name'],
1507 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1508 $groupTree[$groupID]['table_name'],
1513 'custom_' . $fieldId,
1519 'entity_table' => $groupTree[$groupID]['table_name'],
1520 'entity_id' => $entityId[1],
1523 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1528 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1532 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1540 * Generic function to build all the form elements for a specific group tree.
1542 * @param CRM_Core_Form $form
1544 * @param array $groupTree
1545 * The group tree object.
1546 * @param bool $inactiveNeeded
1547 * Return inactive custom groups.
1548 * @param string $prefix
1549 * Prefix for custom grouptree assigned to template.
1551 * @throws \CiviCRM_API3_Exception
1553 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1554 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1556 foreach ($groupTree as $id => $group) {
1557 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1558 foreach ($group['fields'] as $field) {
1559 $required = CRM_Utils_Array
::value('is_required', $field);
1561 if ($field['data_type'] == 'File') {
1562 if (!empty($field['element_value']['data'])) {
1567 $fieldId = $field['id'];
1568 $elementName = $field['element_name'];
1569 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1570 if ($form->getAction() == CRM_Core_Action
::VIEW
) {
1571 $form->getElement($elementName)->freeze();
1578 * Extract the get params from the url, validate and store it in session.
1580 * @param CRM_Core_Form $form
1582 * @param string $type
1583 * The type of custom group we are using.
1586 * @throws \CRM_Core_Exception
1587 * @throws \CiviCRM_API3_Exception
1589 public static function extractGetParams(&$form, $type) {
1594 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1603 foreach ($groupTree as $group) {
1604 if (!isset($group['fields'])) {
1607 foreach ($group['fields'] as $key => $field) {
1608 $fieldName = 'custom_' . $key;
1609 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1613 if (!in_array($field['html_type'], $htmlType) ||
1614 $field['data_type'] == 'Boolean'
1616 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1618 if ($field['html_type'] == 'CheckBox' ||
1619 $field['html_type'] == 'Multi-Select'
1621 $value = str_replace("|", ",", $value);
1622 $mulValues = explode(',', $value);
1623 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1625 foreach ($mulValues as $v1) {
1626 foreach ($customOption as $coID => $coValue) {
1627 if (strtolower(trim($coValue['label'])) ==
1628 strtolower(trim($v1))
1630 $val[$coValue['value']] = 1;
1642 elseif ($field['html_type'] == 'Select' ||
1643 ($field['html_type'] == 'Radio' &&
1644 $field['data_type'] != 'Boolean'
1647 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1648 foreach ($customOption as $customID => $coValue) {
1649 if (strtolower(trim($coValue['label'])) ==
1650 strtolower(trim($value))
1652 $value = $coValue['value'];
1657 elseif ($field['data_type'] == 'Date') {
1658 $valid = CRM_Utils_Rule
::date($value);
1662 $customValue[$fieldName] = $value;
1668 return $customValue;
1672 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1673 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1675 * @param int $customFieldId
1677 * @param array $removeCustomFieldTypes
1678 * Remove custom fields of a type eg: array("Individual") ;.
1681 * false if it matches else true
1683 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1684 $query = "SELECT cg.extends as extends
1685 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1686 WHERE cg.id = cf.custom_group_id
1688 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1690 $extends = CRM_Core_DAO
::singleValueQuery($query);
1692 if (in_array($extends, $removeCustomFieldTypes)) {
1704 public static function mapTableName($table) {
1709 case 'Organization':
1710 return 'civicrm_contact';
1713 return 'civicrm_activity';
1716 return 'civicrm_group';
1718 case 'Contribution':
1719 return 'civicrm_contribution';
1721 case 'ContributionRecur':
1722 return 'civicrm_contribution_recur';
1724 case 'Relationship':
1725 return 'civicrm_relationship';
1728 return 'civicrm_event';
1731 return 'civicrm_membership';
1734 case 'ParticipantRole':
1735 case 'ParticipantEventName':
1736 case 'ParticipantEventType':
1737 return 'civicrm_participant';
1740 return 'civicrm_grant';
1743 return 'civicrm_pledge';
1746 return 'civicrm_address';
1749 return 'civicrm_campaign';
1753 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1754 $qParams = [1 => [$table, 'String']];
1755 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1758 return 'civicrm_contact';
1761 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1762 if (array_key_exists($table, $extendObjs)) {
1763 return $extendObjs[$table];
1765 CRM_Core_Error
::fatal();
1773 * @throws \Exception
1775 public static function createTable($group) {
1777 'name' => $group->table_name
,
1778 'is_multiple' => $group->is_multiple ?
1 : 0,
1779 'extends_name' => self
::mapTableName($group->extends),
1782 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1784 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1788 * Function returns formatted groupTree, so that form can be easily built in template
1790 * @param array $groupTree
1791 * @param int $groupCount
1792 * Group count by default 1, but can vary for multiple value custom data.
1793 * @param \CRM_Core_Form $form
1796 * @throws \CRM_Core_Exception
1798 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1799 $formattedGroupTree = [];
1800 $uploadNames = $formValues = [];
1802 // retrieve qf key from url
1803 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1805 // fetch submitted custom field values later use to set as a default values
1807 $submittedValues = Civi
::cache('customData')->get($qfKey);
1810 foreach ($groupTree as $key => $value) {
1811 if ($key === 'info') {
1815 // add group information
1816 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1817 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1818 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1819 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1820 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1821 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1822 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1824 // this params needed of bulding multiple values
1825 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1826 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1827 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1828 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1829 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1830 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1832 // add field information
1833 foreach ($value['fields'] as $k => $properties) {
1834 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1835 if (isset($properties['customValue']) &&
1836 !CRM_Utils_System
::isNull($properties['customValue']) &&
1837 !isset($properties['element_value'])
1839 if (isset($properties['customValue'][$groupCount])) {
1840 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1841 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1842 if ($properties['data_type'] == 'File') {
1843 $properties['element_value'] = $properties['customValue'][$groupCount];
1844 $uploadNames[] = $properties['element_name'];
1847 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1851 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1852 $formValues[$properties['element_name']] = $value;
1854 elseif (isset($submittedValues[$properties['element_name']])) {
1855 $properties['element_value'] = $submittedValues[$properties['element_name']];
1857 unset($properties['customValue']);
1858 $formattedGroupTree[$key]['fields'][$k] = $properties;
1863 if (count($formValues)) {
1864 $qf = $form->get('qfKey');
1865 $form->assign('qfKey', $qf);
1866 Civi
::cache('customData')->set($qf, $formValues);
1869 // hack for field type File
1870 $formUploadNames = $form->get('uploadNames');
1871 if (is_array($formUploadNames)) {
1872 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1875 $form->set('uploadNames', $uploadNames);
1878 return $formattedGroupTree;
1882 * Build custom data view.
1884 * @param CRM_Core_Form|CRM_Core_Page $form
1886 * @param array $groupTree
1887 * @param bool $returnCount
1888 * True if customValue count needs to be returned.
1890 * @param null $prefix
1891 * @param int $customValueId
1892 * @param int $entityId
1895 * @throws \Exception
1897 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1899 foreach ($groupTree as $key => $group) {
1900 if ($key === 'info') {
1904 foreach ($group['fields'] as $k => $properties) {
1905 $groupID = $group['id'];
1906 if (!empty($properties['customValue'])) {
1907 foreach ($properties['customValue'] as $values) {
1908 if (!empty($customValueId) && $customValueId != $values['id']) {
1911 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1912 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1913 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1914 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1915 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1916 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1917 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1918 $details[$groupID][$values['id']]['fields'][$k] = [
1919 'field_title' => CRM_Utils_Array
::value('label', $properties),
1920 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1921 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1922 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1923 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1925 // editable = whether this set contains any non-read-only fields
1926 if (!isset($details[$groupID][$values['id']]['editable'])) {
1927 $details[$groupID][$values['id']]['editable'] = FALSE;
1929 if (empty($properties['is_view'])) {
1930 $details[$groupID][$values['id']]['editable'] = TRUE;
1932 // also return contact reference contact id if user has view all or edit all contacts perm
1933 if ((CRM_Core_Permission
::check('view all contacts') ||
1934 CRM_Core_Permission
::check('edit all contacts'))
1936 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1939 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1944 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1945 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1946 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1947 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1948 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1949 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1950 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
1951 $details[$groupID][0]['fields'][$k] = ['field_title' => CRM_Utils_Array
::value('label', $properties)];
1957 // return a single value count if group id is passed to function
1958 // else return a groupId and count mapped array
1960 return count($details[$gID]);
1964 foreach ($details as $key => $value) {
1965 $countValue[$key] = count($details[$key]);
1971 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1977 * Get the custom group titles by custom field ids.
1979 * @param array $fieldIds
1980 * Array of custom field ids.
1982 * @return array|NULL
1983 * array consisting of groups and fields labels with ids.
1985 public static function getGroupTitles($fieldIds) {
1986 if (!is_array($fieldIds) && empty($fieldIds)) {
1991 $fIds = "(" . implode(',', $fieldIds) . ")";
1994 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1995 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1996 FROM civicrm_custom_group, civicrm_custom_field
1997 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1998 AND civicrm_custom_field.id IN {$fIds}";
2000 $dao = CRM_Core_DAO
::executeQuery($query);
2001 while ($dao->fetch()) {
2002 $groupLabels[$dao->fieldID
] = [
2003 'fieldID' => $dao->fieldID
,
2004 'fieldLabel' => $dao->fieldLabel
,
2005 'groupID' => $dao->groupID
,
2006 'groupTitle' => $dao->groupTitle
,
2010 return $groupLabels;
2013 public static function dropAllTables() {
2014 $query = "SELECT table_name FROM civicrm_custom_group";
2015 $dao = CRM_Core_DAO
::executeQuery($query);
2017 while ($dao->fetch()) {
2018 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2019 CRM_Core_DAO
::executeQuery($query);
2024 * Check whether custom group is empty or not.
2030 * true if empty otherwise false.
2032 public static function isGroupEmpty($gID) {
2037 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2042 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2043 $value = CRM_Core_DAO
::singleValueQuery($query);
2045 if (empty($value)) {
2053 * Get the list of types for objects that a custom group extends to.
2055 * @param array $types
2056 * Var which should have the list appended.
2060 * @throws \Exception
2062 public static function getExtendedObjectTypes(&$types = []) {
2063 static $flag = FALSE, $objTypes = [];
2067 CRM_Core_OptionValue
::getValues(['name' => 'cg_extend_objects'], $extendObjs);
2069 foreach ($extendObjs as $ovId => $ovValues) {
2070 if ($ovValues['description']) {
2071 // description is expected to be a callback func to subtypes
2072 list($callback, $args) = explode(';', trim($ovValues['description']));
2078 if (!is_array($args)) {
2079 CRM_Core_Error
::fatal('Arg is not of type array');
2082 list($className) = explode('::', $callback);
2083 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
2085 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2091 $types = array_merge($types, $objTypes);
2096 * @param int $customGroupId
2097 * @param int $entityId
2101 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2102 // check whether the group is multiple
2103 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2104 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2105 $hasReachedMax = FALSE;
2107 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2109 if (!$maxMultiple) {
2110 $hasReachedMax = FALSE;
2113 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2114 // count the number of entries for a entity
2115 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2116 $params = [1 => [$entityId, 'Integer']];
2117 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2119 if ($count >= $maxMultiple) {
2120 $hasReachedMax = TRUE;
2124 return $hasReachedMax;
2130 public static function getMultipleFieldGroup() {
2131 $multipleGroup = [];
2132 $dao = new CRM_Core_DAO_CustomGroup();
2133 $dao->is_multiple
= 1;
2134 $dao->is_active
= 1;
2136 while ($dao->fetch()) {
2137 $multipleGroup[$dao->id
] = $dao->title
;
2139 return $multipleGroup;
2143 * Build the metadata tree for the custom group.
2145 * @param string $entityType
2146 * @param array $toReturn
2147 * @param array $subTypes
2148 * @param string $queryString
2149 * @param array $params
2150 * @param string $subType
2153 * @throws \CRM_Core_Exception
2155 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2156 $groupTree = $multipleFieldGroups = [];
2157 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
2158 $customValueTables = [];
2161 while ($crmDAO->fetch()) {
2163 $groupID = $crmDAO->civicrm_custom_group_id
;
2164 $fieldId = $crmDAO->civicrm_custom_field_id
;
2165 if ($crmDAO->civicrm_custom_group_is_multiple
) {
2166 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
2168 // create an array for groups if it does not exist
2169 if (!array_key_exists($groupID, $groupTree)) {
2170 $groupTree[$groupID] = [];
2171 $groupTree[$groupID]['id'] = $groupID;
2173 // populate the group information
2174 foreach ($toReturn['custom_group'] as $fieldName) {
2175 $fullFieldName = "civicrm_custom_group_$fieldName";
2176 if ($fieldName == 'id' ||
2177 is_null($crmDAO->$fullFieldName)
2182 // This is an old bit of code - per the CRM number & probably does not work reliably if
2183 // that one contact sub-type exists.
2184 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2185 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
2187 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2189 $groupTree[$groupID]['fields'] = [];
2191 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = [];
2194 // add the fields now (note - the query row will always contain a field)
2195 // we only reset this once, since multiple values come is as multiple rows
2196 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2197 $groupTree[$groupID]['fields'][$fieldId] = [];
2200 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
2201 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2202 // populate information for a custom field
2203 foreach ($toReturn['custom_field'] as $fieldName) {
2204 $fullFieldName = "civicrm_custom_field_$fieldName";
2205 if ($fieldName == 'id' ||
2206 is_null($crmDAO->$fullFieldName)
2210 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2214 if (!empty($customValueTables)) {
2215 $groupTree['info'] = ['tables' => $customValueTables];
2217 return [$multipleFieldGroups, $groupTree];