3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * Business object for managing custom data groups.
37 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
42 public function __construct() {
43 parent
::__construct();
47 * Takes an associative array and creates a custom group object.
49 * This function is invoked from within the web form layer and also from the api layer
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
54 * @return CRM_Core_DAO_CustomGroup
57 public static function create(&$params) {
58 // create custom group dao, populate fields and then save.
59 $group = new CRM_Core_DAO_CustomGroup();
60 if (isset($params['title'])) {
61 $group->title
= $params['title'];
64 $extends = CRM_Utils_Array
::value('extends', $params, []);
65 $extendsEntity = CRM_Utils_Array
::value(0, $extends);
67 $participantEntities = [
69 'ParticipantEventName',
70 'ParticipantEventType',
73 if (in_array($extendsEntity, $participantEntities)) {
74 $group->extends = 'Participant';
77 $group->extends = $extendsEntity;
80 $group->extends_entity_column_id
= 'null';
81 if (in_array($extendsEntity, $participantEntities)
83 $group->extends_entity_column_id
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $extendsEntity, 'value', 'name');
86 // this is format when form get submit.
87 $extendsChildType = CRM_Utils_Array
::value(1, $extends);
88 // lets allow user to pass direct child type value, CRM-6893
89 if (!empty($params['extends_entity_column_value'])) {
90 $extendsChildType = $params['extends_entity_column_value'];
92 if (!CRM_Utils_System
::isNull($extendsChildType)) {
93 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
94 if (CRM_Utils_Array
::value(0, $extends) == 'Relationship') {
95 $extendsChildType = str_replace(['_a_b', '_b_a'], [
98 ], $extendsChildType);
100 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
101 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
102 CRM_Core_DAO
::VALUE_SEPARATOR
;
106 $extendsChildType = 'null';
108 $group->extends_entity_column_value
= $extendsChildType;
110 if (isset($params['id'])) {
111 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
116 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
120 'collapse_adv_display',
126 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
127 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
128 if ($is_public_version) {
129 $fields[] = 'is_public';
131 foreach ($fields as $field) {
132 if (isset($params[$field])) {
133 $group->$field = $params[$field];
136 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
137 $params['max_multiple'] >= '0'
138 ) ?
$params['max_multiple'] : 'null' : 'null';
140 $tableName = $tableNameNeedingIndexUpdate = NULL;
141 if (isset($params['id'])) {
142 $group->id
= $params['id'];
144 if (isset($params['is_multiple'])) {
145 // check whether custom group was changed from single-valued to multiple-valued
146 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
151 // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
152 $paramsIsMultiple = empty($params['is_multiple']) ?
0 : 1;
153 if ($paramsIsMultiple != $isMultiple) {
154 $tableNameNeedingIndexUpdate = CRM_Core_DAO
::getFieldValue(
155 'CRM_Core_DAO_CustomGroup',
163 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
164 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
166 // we do this only once, so name never changes
167 if (isset($params['name'])) {
168 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
171 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
174 if (isset($params['table_name'])) {
175 $tableName = $params['table_name'];
177 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
178 // Bad idea. Prevent group creation because it might lead to a broken configuration.
179 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", ['1' => $tableName]));
184 if (array_key_exists('is_reserved', $params)) {
185 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
187 $op = isset($params['id']) ?
'edit' : 'create';
188 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
190 // enclose the below in a transaction
191 $transaction = new CRM_Core_Transaction();
194 if (!isset($params['id'])) {
195 if (!isset($params['table_name'])) {
196 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 13));
197 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
199 $group->table_name
= $tableName;
200 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
206 // now create the table associated with this group
207 self
::createTable($group);
209 elseif ($tableNameNeedingIndexUpdate) {
210 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array
::value('is_multiple', $params));
213 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
214 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
218 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($extendsEntity));
220 $transaction->commit();
223 CRM_Utils_System
::flushCache();
226 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
229 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
236 * Fetch object based on array of properties.
238 * @param array $params
239 * (reference ) an assoc array of name/value pairs.
240 * @param array $defaults
241 * (reference ) an assoc array to hold the flattened values.
243 * @return CRM_Core_DAO_CustomGroup
245 public static function retrieve(&$params, &$defaults) {
246 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
250 * Update the is_active flag in the db.
253 * Id of the database record.
254 * @param bool $is_active
255 * Value we want to set the is_active field.
258 * true if we found and updated the object, else false
260 public static function setIsActive($id, $is_active) {
262 Civi
::cache('fields')->flush();
263 // reset ACL and system caches.
264 CRM_Core_BAO_Cache
::resetCaches();
267 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
270 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
274 * Determine if given entity (sub)type has any custom groups
276 * @param string $extends
277 * E.g. "Individual", "Activity".
278 * @param int $columnId
279 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
280 * @param string $columnValue
281 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
285 public static function hasCustomGroup($extends, $columnId, $columnValue) {
286 $dao = new CRM_Core_DAO_CustomGroup();
287 $dao->extends = $extends;
288 $dao->extends_entity_column_id
= $columnId;
289 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
290 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
291 //$dao->extends_entity_column_value = $columnValue;
292 return $dao->find() ?
TRUE : FALSE;
296 * Determine if there are any CustomGroups for the given $activityTypeId.
297 * If none found, create one.
299 * @param int $activityTypeId
302 * TRUE if a group is found or created; FALSE on error
304 public static function autoCreateByActivityType($activityTypeId) {
305 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
309 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
312 'extends' => 'Activity',
313 'extends_entity_column_id' => NULL,
314 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded([$activityTypeId]),
315 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
319 $result = civicrm_api('CustomGroup', 'create', $params);
320 return !$result['is_error'];
324 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
325 * This may also include entity specific data values.
327 * An array containing all custom groups and their custom fields is returned.
329 * @param string $entityType
330 * Of the contact whose contact type is needed.
331 * @param array $toReturn
332 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
333 * @param int $entityID
334 * @param int $groupID
335 * @param array $subTypes
336 * @param string $subName
337 * @param bool $fromCache
338 * @param bool $onlySubType
339 * Only return specified subtype or return specified subtype + unrestricted fields.
340 * @param bool $returnAll
341 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
342 * api - through which it is properly tested - so can be refactored with some comfort.)
344 * @param bool $checkPermission
345 * @param string|int $singleRecord
346 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
347 * @param bool $showPublicOnly
350 * Custom field 'tree'.
352 * The returned array is keyed by group id and has the custom group table fields
353 * and a subkey 'fields' holding the specific custom fields.
354 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
355 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
357 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
358 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
359 * With caching the performance impact would be small & the function would be cleaner
361 * @throws \CRM_Core_Exception
363 public static function getTree(
373 $checkPermission = TRUE,
374 $singleRecord = NULL,
375 $showPublicOnly = FALSE
378 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
380 if (!is_array($subTypes)) {
381 if (empty($subTypes)) {
385 if (stristr($subTypes, ',')) {
386 $subTypes = explode(',', $subTypes);
389 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
396 // legacy hardcoded list of data to return
430 'extends_entity_column_id',
431 'extends_entity_column_value',
435 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
436 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
437 if ($is_public_version) {
438 $tableData['custom_group'][] = 'is_public';
440 if (!$toReturn ||
!is_array($toReturn)) {
441 $toReturn = $tableData;
444 // Supply defaults and remove unknown array keys
445 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
446 // Merge in required fields that we must have
447 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
448 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
449 // Validate return fields
450 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
451 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
456 foreach ($toReturn as $tableName => $tableColumn) {
457 foreach ($tableColumn as $columnName) {
458 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
461 $strSelect = "SELECT " . implode(', ', $select);
463 // from, where, order by
465 FROM civicrm_custom_group
466 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
469 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
470 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
471 $entityType == 'Household'
473 $in = "'$entityType', 'Contact'";
475 elseif (strpos($entityType, "'") !== FALSE) {
476 // this allows the calling function to send in multiple entity types
481 $in = "'$entityType'";
487 if (!empty($subTypes)) {
488 foreach ($subTypes as $key => $subType) {
489 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
491 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
493 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
497 WHERE civicrm_custom_group.is_active = 1
498 AND civicrm_custom_field.is_active = 1
499 AND civicrm_custom_group.extends IN ($in)
503 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
504 $params[$sqlParamKey] = [$subName, 'String'];
505 $sqlParamKey = $sqlParamKey +
1;
510 WHERE civicrm_custom_group.is_active = 1
511 AND civicrm_custom_field.is_active = 1
512 AND civicrm_custom_group.extends IN ($in)
515 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
520 // since we want a specific group id we add it to the where clause
521 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
522 $params[$sqlParamKey] = [$groupID, 'Integer'];
525 // since groupID is false we need to show all Inline groups
526 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
528 if ($checkPermission) {
529 // ensure that the user has access to these custom groups
530 $strWhere .= " AND " .
531 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
532 'civicrm_custom_group.'
536 if ($showPublicOnly && $is_public_version) {
537 $strWhere .= "AND civicrm_custom_group.is_public = 1";
541 ORDER BY civicrm_custom_group.weight,
542 civicrm_custom_group.title,
543 civicrm_custom_field.weight,
544 civicrm_custom_field.label
547 // final query string
548 $queryString = "$strSelect $strFrom $strWhere $orderBy";
550 // lets see if we can retrieve the groupTree from cache
551 $cacheString = $queryString;
553 $cacheString .= "_{$groupID}";
556 $cacheString .= "_Inline";
559 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
560 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
561 $cache = CRM_Utils_Cache
::singleton();
563 $groupTree = $cache->get($cacheKey);
564 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
567 if (empty($groupTree)) {
568 list($multipleFieldGroups, $groupTree) = self
::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType);
570 $cache->set($cacheKey, $groupTree);
571 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
573 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
574 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
575 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
576 $singleFieldTables = [];
577 // now that we have all the groups and fields, lets get the values
578 // since we need to know the table and field names
579 // add info to groupTree
581 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
582 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
584 $select = $from = $where = [];
585 $groupTree['info']['where'] = NULL;
587 foreach ($groupTree['info']['tables'] as $table => $fields) {
588 $groupTree['info']['from'][] = $table;
590 "{$table}.id as {$table}_id",
591 "{$table}.entity_id as {$table}_entity_id",
593 foreach ($fields as $column => $dontCare) {
594 $select[] = "{$table}.{$column} as {$table}_{$column}";
596 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
598 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
599 if (in_array($table, $multipleFieldGroups) &&
600 self
::customGroupDataExistsForEntity($entityID, $table)
602 $entityMultipleSelectClauses[$table] = $select;
605 $singleFieldTables[] = $table;
606 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
611 if ($entityID && !empty($singleFieldTables)) {
612 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
614 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
615 if (!empty($multipleFieldTablesWithEntityData)) {
616 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
624 * Clean and validate the filter before it is used in a db query.
626 * @param string $entityType
627 * @param string $subType
630 * @throws \CRM_Core_Exception
632 protected static function validateSubTypeByEntity($entityType, $subType) {
633 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
634 if (is_numeric($subType)) {
638 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
639 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
641 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
642 throw new CRM_Core_Exception('Invalid Entity Filter');
644 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
645 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
646 if (!array_key_exists($subType, $subTypes)) {
647 throw new CRM_Core_Exception('Invalid Filter');
653 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
654 * a WHERE condition for rows that include $value. Use whereListHas().
656 * @param string $column
657 * @param string $value
658 * @param string $delimiter
662 private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
664 $bareValue = trim($value, $delimiter);
665 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
666 return "($column LIKE \"$escapedValue\")";
670 * Check whether the custom group has any data for the given entity.
672 * @param int $entityID
673 * Id of entity for whom we are checking data for.
674 * @param string $table
675 * Table that we are checking.
677 * @param bool $getCount
680 * does this entity have data in this custom table
682 public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
686 WHERE entity_id = $entityID
688 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
690 return $recordExists;
692 return $recordExists ?
TRUE : FALSE;
696 * Build the group tree for Custom fields which are not 'is_multiple'
698 * The combination of all these fields in one query with a 'using' join was not working for
699 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
700 * mechanism as it seemed to be acceptable in this context
702 * @param array $groupTree
703 * (reference) group tree array which is being built.
704 * @param int $entityID
705 * Id of entity for whom the tree is being build up.
706 * @param array $entitySingleSelectClauses
707 * Array of select clauses relevant to the entity.
708 * @param array $singleFieldTablesWithEntityData
709 * Array of tables in which this entity has data.
711 public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
712 $select = implode(', ', $entitySingleSelectClauses);
713 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
714 foreach ($singleFieldTablesWithEntityData as $table) {
715 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
721 WHERE first.entity_id = $entityID
723 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
727 * Build the group tree for Custom fields which are 'is_multiple'
729 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
731 * @param array $groupTree
732 * (reference) group tree array which is being built.
733 * @param int $entityID
734 * Id of entity for whom the tree is being build up.
735 * @param array $entityMultipleSelectClauses
736 * Array of select clauses relevant to the entity.
737 * @param array $multipleFieldTablesWithEntityData
738 * Array of tables in which this entity has data.
739 * @param string|int $singleRecord
740 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
742 public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
743 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
744 $select = implode(',', $selectClauses);
748 WHERE entity_id = $entityID
751 $offset = $singleRecord - 1;
752 $query .= " LIMIT {$offset}, 1";
754 self
::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
759 * Build the tree entity data - starting from a query retrieving the custom fields build the group
760 * tree data for the relevant entity (entity is included in the query).
762 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
764 * @param array $groupTree
765 * (reference) group tree array which is being built.
766 * @param string $query
767 * @param array $includedTables
768 * Tables to include - required because the function (for historical reasons).
769 * iterates through the group tree
770 * @param string|int $singleRecord
771 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
773 public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
774 $dao = CRM_Core_DAO
::executeQuery($query);
775 while ($dao->fetch()) {
776 foreach ($groupTree as $groupID => $group) {
777 if ($groupID === 'info') {
780 $table = $groupTree[$groupID]['table_name'];
781 //working from the groupTree instead of the table list means we have to iterate & exclude.
782 // this could possibly be re-written as other parts of the function have been refactored
783 // for now we just check if the given table is to be included in this function
784 if (!in_array($table, $includedTables)) {
787 foreach ($group['fields'] as $fieldID => $dontCare) {
788 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
795 * Build the entity-specific custom data into the group tree on a per-field basis
798 * Object representing the custom field to be populated into the groupTree.
799 * @param array $groupTree
800 * (reference) the group tree being build.
801 * @param string $table
803 * @param int $groupID
805 * @param int $fieldID
807 * @param string|int $singleRecord
808 * holds 'new' or id if loading view/edit/copy for a single record.
810 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
811 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
812 $idName = "{$table}_id";
813 $fieldName = "{$table}_{$column}";
814 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
815 if ($dataType == 'File') {
816 if (isset($dao->$fieldName)) {
817 $config = CRM_Core_Config
::singleton();
818 $fileDAO = new CRM_Core_DAO_File();
819 $fileDAO->id
= $dao->$fieldName;
821 if ($fileDAO->find(TRUE)) {
822 $entityIDName = "{$table}_entity_id";
823 $fileHash = CRM_Core_BAO_File
::generateFileHash($dao->$entityIDName, $fileDAO->id
);
824 $customValue['id'] = $dao->$idName;
825 $customValue['data'] = $fileDAO->uri
;
826 $customValue['fid'] = $fileDAO->id
;
827 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
828 $customValue['displayURL'] = NULL;
829 $deleteExtra = ts('Are you sure you want to delete attached file.');
831 CRM_Core_Action
::DELETE
=> [
832 'name' => ts('Delete Attached File'),
833 'url' => 'civicrm/file',
834 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
835 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
836 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
839 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
840 CRM_Core_Action
::DELETE
,
842 'id' => $fileDAO->id
,
843 'eid' => $dao->$entityIDName,
849 'file.manage.delete',
853 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
854 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
855 if ($fileDAO->mime_type
== "image/jpeg" ||
856 $fileDAO->mime_type
== "image/pjpeg" ||
857 $fileDAO->mime_type
== "image/gif" ||
858 $fileDAO->mime_type
== "image/x-png" ||
859 $fileDAO->mime_type
== "image/png"
861 $customValue['displayURL'] = $customValue['fileURL'];
862 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
867 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
869 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId);
870 if ($path && file_exists($path)) {
871 list($imageWidth, $imageHeight) = getimagesize($path);
872 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
873 $customValue['imageThumbWidth'] = $imageThumbWidth;
874 $customValue['imageThumbHeight'] = $imageThumbHeight;
881 'id' => $dao->$idName,
888 'id' => $dao->$idName,
889 'data' => $dao->$fieldName,
893 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
894 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
896 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
897 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
899 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
900 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
903 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
908 * Get the group title.
916 public static function getTitle($id) {
917 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
921 * Get custom group details for a group.
923 * An array containing custom group details (including their custom field) is returned.
925 * @param int $groupId
926 * Group id whose details are needed.
927 * @param bool $searchable
928 * Is this field searchable.
929 * @param array $extends
930 * Which table does it extend if any.
932 * @param bool $inSelector
935 * array consisting of all group and field details
937 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
941 // using tableData to build the queryString
943 'civicrm_custom_field' => [
967 'civicrm_custom_group' => [
974 'collapse_adv_display',
976 'extends_entity_column_value',
984 foreach ($tableData as $tableName => $tableColumn) {
985 foreach ($tableColumn as $columnName) {
986 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
989 $select = 'SELECT ' . implode(', ', $s);
991 // from, where, order by
992 $from = " FROM civicrm_custom_field, civicrm_custom_group";
993 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
994 AND civicrm_custom_group.is_active = 1
995 AND civicrm_custom_field.is_active = 1 ";
997 $params[1] = [$groupId, 'Integer'];
998 $where .= " AND civicrm_custom_group.id = %1";
1002 $where .= " AND civicrm_custom_field.is_searchable = 1";
1006 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1011 foreach ($extends as $e) {
1012 $clause[] = "civicrm_custom_group.extends = '$e'";
1014 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1016 //include case activities customdata if case is enabled
1017 if (in_array('Activity', $extends)) {
1018 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1019 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1020 $params[2] = [CRM_Core_DAO
::VALUE_SEPARATOR
, 'String'];
1024 // ensure that the user has access to these custom groups
1026 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1027 'civicrm_custom_group.'
1030 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1032 // final query string
1033 $queryString = $select . $from . $where . $orderBy;
1036 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1039 while ($crmDAO->fetch()) {
1040 $groupId = $crmDAO->civicrm_custom_group_id
;
1041 $fieldId = $crmDAO->civicrm_custom_field_id
;
1043 // create an array for groups if it does not exist
1044 if (!array_key_exists($groupId, $groupTree)) {
1045 $groupTree[$groupId] = [];
1046 $groupTree[$groupId]['id'] = $groupId;
1048 foreach ($tableData['civicrm_custom_group'] as $v) {
1049 $fullField = "civicrm_custom_group_" . $v;
1051 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1055 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1058 $groupTree[$groupId]['fields'] = [];
1061 // add the fields now (note - the query row will always contain a field)
1062 $groupTree[$groupId]['fields'][$fieldId] = [];
1063 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1065 foreach ($tableData['civicrm_custom_field'] as $v) {
1066 $fullField = "civicrm_custom_field_" . $v;
1067 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1070 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1078 * @param $entityType
1080 * @param string $cidToken
1084 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1086 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1088 // get 'Tab' and 'Tab with table' groups
1089 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1090 $customGroupDAO->whereAdd("is_active = 1");
1092 // add whereAdd for entity type
1093 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1097 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1098 $customGroupDAO->whereAdd($permissionClause);
1101 $customGroupDAO->orderBy('weight');
1102 $customGroupDAO->find();
1104 // process each group with menu tab
1105 while ($customGroupDAO->fetch()) {
1107 $group['id'] = $customGroupDAO->id
;
1108 $group['path'] = $path;
1109 $group['title'] = "$customGroupDAO->title";
1110 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1111 $group['extra'] = ['gid' => $customGroupDAO->id
];
1112 $group['table_name'] = $customGroupDAO->table_name
;
1113 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1121 * Get the table name for the entity type
1122 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1123 * tableName is 'civicrm_contact'
1125 * @param string $entityType
1126 * What entity are we extending here ?.
1131 * @see _apachesolr_civiAttachments_dereference_file_parent
1133 public static function getTableNameByEntityName($entityType) {
1135 switch ($entityType) {
1139 case 'Organization':
1140 $tableName = 'civicrm_contact';
1143 case 'Contribution':
1144 $tableName = 'civicrm_contribution';
1148 $tableName = 'civicrm_group';
1151 // DRAFTING: Verify if we cannot make it pluggable
1154 $tableName = 'civicrm_activity';
1157 case 'Relationship':
1158 $tableName = 'civicrm_relationship';
1162 $tableName = 'civicrm_membership';
1166 $tableName = 'civicrm_participant';
1170 $tableName = 'civicrm_event';
1174 $tableName = 'civicrm_grant';
1177 // need to add cases for Location, Address
1184 * Get a list of custom groups which extend a given entity type.
1185 * If there are custom-groups which only apply to certain subtypes,
1186 * those WILL be included.
1188 * @param string $entityType
1190 * @return CRM_Core_DAO_CustomGroup
1192 public static function getAllCustomGroupsByBaseEntity($entityType) {
1193 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1194 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1195 return $customGroupDAO;
1199 * Add the whereAdd clause for the DAO depending on the type of entity
1200 * the custom group is extending.
1202 * @param object $customGroupDAO
1203 * @param string $entityType
1204 * What entity are we extending here ?.
1206 * @param int $entityID
1207 * @param bool $allSubtypes
1209 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1210 $addSubtypeClause = FALSE;
1211 // This function isn't really accessible with user data but since the string
1212 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1214 $entityType = CRM_Core_DAO
::escapeString($entityType);
1216 switch ($entityType) {
1218 // if contact, get all related to contact
1219 $extendList = "'Contact','Individual','Household','Organization'";
1220 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1221 if (!$allSubtypes) {
1222 $addSubtypeClause = TRUE;
1228 case 'Organization':
1229 // is I/H/O then get I/H/O and contact
1230 $extendList = "'Contact','$entityType'";
1231 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1232 if (!$allSubtypes) {
1233 $addSubtypeClause = TRUE;
1238 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1242 if ($addSubtypeClause) {
1243 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1245 if (!empty($csType)) {
1246 $subtypeClause = [];
1247 foreach ($csType as $subtype) {
1248 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1249 CRM_Core_DAO
::VALUE_SEPARATOR
;
1250 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1252 $subtypeClause[] = "extends_entity_column_value IS NULL";
1253 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1257 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1263 * Delete the Custom Group.
1265 * @param CRM_Core_BAO_CustomGroup $group
1266 * Custom group object.
1267 * @param bool $force
1268 * whether to force the deletion, even if there are custom fields.
1271 * False if field exists for this group, true if group gets deleted.
1273 public static function deleteGroup($group, $force = FALSE) {
1275 //check whether this contain any custom fields
1276 $customField = new CRM_Core_DAO_CustomField();
1277 $customField->custom_group_id
= $group->id
;
1278 $customField->find();
1280 // return early if there are custom fields and we're not
1281 // forcing the delete, otherwise delete the fields one by one
1282 while ($customField->fetch()) {
1286 CRM_Core_BAO_CustomField
::deleteField($customField);
1289 // drop the table associated with this custom group
1290 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1292 //delete custom group
1295 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1303 * @param array $groupTree
1304 * @param array $defaults
1305 * @param bool $viewMode
1306 * @param bool $inactiveNeeded
1307 * @param int $action
1309 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1310 foreach ($groupTree as $id => $group) {
1311 if (!isset($group['fields'])) {
1314 foreach ($group['fields'] as $field) {
1315 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1316 $value = $field['element_value'];
1318 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1319 ($action != CRM_Core_Action
::UPDATE ||
1321 !array_key_exists('element_value', $field)
1324 $value = $viewMode ?
NULL : $field['default_value'];
1330 if (empty($field['element_name'])) {
1334 $elementName = $field['element_name'];
1336 switch ($field['html_type']) {
1337 case 'Multi-Select':
1339 $defaults[$elementName] = [];
1340 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1342 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1343 if (isset($value)) {
1344 foreach ($customOption as $customValue => $customLabel) {
1345 if (in_array($customValue, $checkedData)) {
1346 if ($field['html_type'] == 'CheckBox') {
1347 $defaults[$elementName][$customValue] = 1;
1350 $defaults[$elementName][$customValue] = $customValue;
1354 $defaults[$elementName][$customValue] = 0;
1360 if (isset($field['customValue']['data'])) {
1361 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1362 foreach ($customOption as $val) {
1363 if (in_array($val['value'], $checkedData)) {
1364 if ($field['html_type'] == 'CheckBox') {
1365 $defaults[$elementName][$val['value']] = 1;
1368 $defaults[$elementName][$val['value']] = $val['value'];
1372 $defaults[$elementName][$val['value']] = 0;
1377 if (is_array($value) && count($value)) {
1378 CRM_Utils_Array
::formatArrayKeys($value);
1379 $checkedValue = $value;
1382 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1384 foreach ($customOption as $val) {
1385 if (in_array($val['value'], $checkedValue)) {
1386 if ($field['html_type'] == 'CheckBox') {
1387 $defaults[$elementName][$val['value']] = 1;
1390 $defaults[$elementName][$val['value']] = $val['value'];
1398 case 'Multi-Select Country':
1399 case 'Multi-Select State/Province':
1400 if (isset($value)) {
1401 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1402 foreach ($checkedValue as $val) {
1404 $defaults[$elementName][$val] = $val;
1410 case 'Select Country':
1412 $defaults[$elementName] = $value;
1415 $config = CRM_Core_Config
::singleton();
1416 $defaults[$elementName] = $config->defaultContactCountry
;
1421 if ($field['data_type'] == "Float") {
1422 $defaults[$elementName] = (float) $value;
1424 elseif ($field['data_type'] == 'Money' &&
1425 $field['html_type'] == 'Text'
1427 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1430 $defaults[$elementName] = $value;
1438 * PostProcess function.
1440 * @param array $groupTree
1441 * @param array $params
1442 * @param bool $skipFile
1444 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1445 // Get the Custom form values and groupTree
1446 // first reset all checkbox and radio data
1447 foreach ($groupTree as $groupID => $group) {
1448 if ($groupID === 'info') {
1451 foreach ($group['fields'] as $field) {
1452 $fieldId = $field['id'];
1454 //added Multi-Select option in the below if-statement
1455 if ($field['html_type'] == 'CheckBox' ||
1456 $field['html_type'] == 'Radio' ||
1457 $field['html_type'] == 'Multi-Select'
1459 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1463 foreach ($params as $key => $val) {
1464 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1465 $match[1] == $field['id']
1471 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1472 // field exists in db so populate value from "form".
1473 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
1476 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1478 // added for CheckBox
1481 $customValue = array_keys($v);
1482 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1483 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1484 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1487 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1491 case 'Multi-Select':
1493 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1494 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1495 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1498 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1503 $date = CRM_Utils_Date
::processDate($v);
1504 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1512 // store the file in d/b
1513 $entityId = explode('=', $groupTree['info']['where'][0]);
1514 $fileParams = ['upload_date' => date('YmdHis')];
1516 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1517 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1520 $fileParams['uri'] = $v['name'];
1521 $fileParams['mime_type'] = $v['type'];
1522 CRM_Core_BAO_File
::filePostProcess($v['name'],
1523 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1524 $groupTree[$groupID]['table_name'],
1529 'custom_' . $fieldId,
1535 'entity_table' => $groupTree[$groupID]['table_name'],
1536 'entity_id' => $entityId[1],
1539 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1544 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1548 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1556 * Generic function to build all the form elements for a specific group tree.
1558 * @param CRM_Core_Form $form
1560 * @param array $groupTree
1561 * The group tree object.
1562 * @param bool $inactiveNeeded
1563 * Return inactive custom groups.
1564 * @param string $prefix
1565 * Prefix for custom grouptree assigned to template.
1567 * @throws \CiviCRM_API3_Exception
1569 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1570 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1572 foreach ($groupTree as $id => $group) {
1573 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1574 foreach ($group['fields'] as $field) {
1575 $required = CRM_Utils_Array
::value('is_required', $field);
1577 if ($field['data_type'] == 'File') {
1578 if (!empty($field['element_value']['data'])) {
1583 $fieldId = $field['id'];
1584 $elementName = $field['element_name'];
1585 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1586 if ($form->getAction() == CRM_Core_Action
::VIEW
) {
1587 $form->getElement($elementName)->freeze();
1594 * Extract the get params from the url, validate and store it in session.
1596 * @param CRM_Core_Form $form
1598 * @param string $type
1599 * The type of custom group we are using.
1602 * @throws \CRM_Core_Exception
1603 * @throws \CiviCRM_API3_Exception
1605 public static function extractGetParams(&$form, $type) {
1610 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1619 foreach ($groupTree as $group) {
1620 if (!isset($group['fields'])) {
1623 foreach ($group['fields'] as $key => $field) {
1624 $fieldName = 'custom_' . $key;
1625 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1629 if (!in_array($field['html_type'], $htmlType) ||
1630 $field['data_type'] == 'Boolean'
1632 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1634 if ($field['html_type'] == 'CheckBox' ||
1635 $field['html_type'] == 'Multi-Select'
1637 $value = str_replace("|", ",", $value);
1638 $mulValues = explode(',', $value);
1639 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1641 foreach ($mulValues as $v1) {
1642 foreach ($customOption as $coID => $coValue) {
1643 if (strtolower(trim($coValue['label'])) ==
1644 strtolower(trim($v1))
1646 $val[$coValue['value']] = 1;
1658 elseif ($field['html_type'] == 'Select' ||
1659 ($field['html_type'] == 'Radio' &&
1660 $field['data_type'] != 'Boolean'
1663 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1664 foreach ($customOption as $customID => $coValue) {
1665 if (strtolower(trim($coValue['label'])) ==
1666 strtolower(trim($value))
1668 $value = $coValue['value'];
1673 elseif ($field['data_type'] == 'Date') {
1674 $valid = CRM_Utils_Rule
::date($value);
1678 $customValue[$fieldName] = $value;
1684 return $customValue;
1688 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1689 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1691 * @param int $customFieldId
1693 * @param array $removeCustomFieldTypes
1694 * Remove custom fields of a type eg: array("Individual") ;.
1697 * false if it matches else true
1699 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1700 $query = "SELECT cg.extends as extends
1701 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1702 WHERE cg.id = cf.custom_group_id
1704 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1706 $extends = CRM_Core_DAO
::singleValueQuery($query);
1708 if (in_array($extends, $removeCustomFieldTypes)) {
1720 public static function mapTableName($table) {
1725 case 'Organization':
1726 return 'civicrm_contact';
1729 return 'civicrm_activity';
1732 return 'civicrm_group';
1734 case 'Contribution':
1735 return 'civicrm_contribution';
1737 case 'ContributionRecur':
1738 return 'civicrm_contribution_recur';
1740 case 'Relationship':
1741 return 'civicrm_relationship';
1744 return 'civicrm_event';
1747 return 'civicrm_membership';
1750 case 'ParticipantRole':
1751 case 'ParticipantEventName':
1752 case 'ParticipantEventType':
1753 return 'civicrm_participant';
1756 return 'civicrm_grant';
1759 return 'civicrm_pledge';
1762 return 'civicrm_address';
1765 return 'civicrm_campaign';
1769 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1770 $qParams = [1 => [$table, 'String']];
1771 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1774 return 'civicrm_contact';
1777 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1778 if (array_key_exists($table, $extendObjs)) {
1779 return $extendObjs[$table];
1781 CRM_Core_Error
::fatal();
1789 * @throws \Exception
1791 public static function createTable($group) {
1793 'name' => $group->table_name
,
1794 'is_multiple' => $group->is_multiple ?
1 : 0,
1795 'extends_name' => self
::mapTableName($group->extends),
1798 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1800 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1804 * Function returns formatted groupTree, so that form can be easily built in template
1806 * @param array $groupTree
1807 * @param int $groupCount
1808 * Group count by default 1, but can vary for multiple value custom data.
1809 * @param \CRM_Core_Form $form
1812 * @throws \CRM_Core_Exception
1814 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1815 $formattedGroupTree = [];
1816 $uploadNames = $formValues = [];
1818 // retrieve qf key from url
1819 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1821 // fetch submitted custom field values later use to set as a default values
1823 $submittedValues = Civi
::cache('customData')->get($qfKey);
1826 foreach ($groupTree as $key => $value) {
1827 if ($key === 'info') {
1831 // add group information
1832 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1833 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1834 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1835 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1836 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1837 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1838 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1840 // this params needed of bulding multiple values
1841 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1842 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1843 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1844 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1845 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1846 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1848 // add field information
1849 foreach ($value['fields'] as $k => $properties) {
1850 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1851 if (isset($properties['customValue']) &&
1852 !CRM_Utils_System
::isNull($properties['customValue']) &&
1853 !isset($properties['element_value'])
1855 if (isset($properties['customValue'][$groupCount])) {
1856 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1857 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1858 if ($properties['data_type'] == 'File') {
1859 $properties['element_value'] = $properties['customValue'][$groupCount];
1860 $uploadNames[] = $properties['element_name'];
1863 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1867 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1868 $formValues[$properties['element_name']] = $value;
1870 elseif (isset($submittedValues[$properties['element_name']])) {
1871 $properties['element_value'] = $submittedValues[$properties['element_name']];
1873 unset($properties['customValue']);
1874 $formattedGroupTree[$key]['fields'][$k] = $properties;
1879 if (count($formValues)) {
1880 $qf = $form->get('qfKey');
1881 $form->assign('qfKey', $qf);
1882 Civi
::cache('customData')->set($qf, $formValues);
1885 // hack for field type File
1886 $formUploadNames = $form->get('uploadNames');
1887 if (is_array($formUploadNames)) {
1888 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1891 $form->set('uploadNames', $uploadNames);
1894 return $formattedGroupTree;
1898 * Build custom data view.
1900 * @param CRM_Core_Form|CRM_Core_Page $form
1902 * @param array $groupTree
1903 * @param bool $returnCount
1904 * True if customValue count needs to be returned.
1906 * @param null $prefix
1907 * @param int $customValueId
1908 * @param int $entityId
1911 * @throws \Exception
1913 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1915 foreach ($groupTree as $key => $group) {
1916 if ($key === 'info') {
1920 foreach ($group['fields'] as $k => $properties) {
1921 $groupID = $group['id'];
1922 if (!empty($properties['customValue'])) {
1923 foreach ($properties['customValue'] as $values) {
1924 if (!empty($customValueId) && $customValueId != $values['id']) {
1927 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1928 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1929 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1930 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1931 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1932 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1933 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1934 $details[$groupID][$values['id']]['fields'][$k] = [
1935 'field_title' => CRM_Utils_Array
::value('label', $properties),
1936 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1937 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1938 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1939 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1941 // editable = whether this set contains any non-read-only fields
1942 if (!isset($details[$groupID][$values['id']]['editable'])) {
1943 $details[$groupID][$values['id']]['editable'] = FALSE;
1945 if (empty($properties['is_view'])) {
1946 $details[$groupID][$values['id']]['editable'] = TRUE;
1948 // also return contact reference contact id if user has view all or edit all contacts perm
1949 if ((CRM_Core_Permission
::check('view all contacts') ||
1950 CRM_Core_Permission
::check('edit all contacts'))
1952 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1955 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1960 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1961 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1962 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1963 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1964 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1965 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1966 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
1967 $details[$groupID][0]['fields'][$k] = ['field_title' => CRM_Utils_Array
::value('label', $properties)];
1973 // return a single value count if group id is passed to function
1974 // else return a groupId and count mapped array
1976 return count($details[$gID]);
1980 foreach ($details as $key => $value) {
1981 $countValue[$key] = count($details[$key]);
1987 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1993 * Get the custom group titles by custom field ids.
1995 * @param array $fieldIds
1996 * Array of custom field ids.
1998 * @return array|NULL
1999 * array consisting of groups and fields labels with ids.
2001 public static function getGroupTitles($fieldIds) {
2002 if (!is_array($fieldIds) && empty($fieldIds)) {
2007 $fIds = "(" . implode(',', $fieldIds) . ")";
2010 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2011 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2012 FROM civicrm_custom_group, civicrm_custom_field
2013 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2014 AND civicrm_custom_field.id IN {$fIds}";
2016 $dao = CRM_Core_DAO
::executeQuery($query);
2017 while ($dao->fetch()) {
2018 $groupLabels[$dao->fieldID
] = [
2019 'fieldID' => $dao->fieldID
,
2020 'fieldLabel' => $dao->fieldLabel
,
2021 'groupID' => $dao->groupID
,
2022 'groupTitle' => $dao->groupTitle
,
2026 return $groupLabels;
2029 public static function dropAllTables() {
2030 $query = "SELECT table_name FROM civicrm_custom_group";
2031 $dao = CRM_Core_DAO
::executeQuery($query);
2033 while ($dao->fetch()) {
2034 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2035 CRM_Core_DAO
::executeQuery($query);
2040 * Check whether custom group is empty or not.
2046 * true if empty otherwise false.
2048 public static function isGroupEmpty($gID) {
2053 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2058 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2059 $value = CRM_Core_DAO
::singleValueQuery($query);
2061 if (empty($value)) {
2069 * Get the list of types for objects that a custom group extends to.
2071 * @param array $types
2072 * Var which should have the list appended.
2076 * @throws \Exception
2078 public static function getExtendedObjectTypes(&$types = []) {
2079 static $flag = FALSE, $objTypes = [];
2083 CRM_Core_OptionValue
::getValues(['name' => 'cg_extend_objects'], $extendObjs);
2085 foreach ($extendObjs as $ovId => $ovValues) {
2086 if ($ovValues['description']) {
2087 // description is expected to be a callback func to subtypes
2088 list($callback, $args) = explode(';', trim($ovValues['description']));
2094 if (!is_array($args)) {
2095 CRM_Core_Error
::fatal('Arg is not of type array');
2098 list($className) = explode('::', $callback);
2099 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
2101 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2107 $types = array_merge($types, $objTypes);
2112 * @param int $customGroupId
2113 * @param int $entityId
2117 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2118 // check whether the group is multiple
2119 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2120 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2121 $hasReachedMax = FALSE;
2123 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2125 if (!$maxMultiple) {
2126 $hasReachedMax = FALSE;
2129 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2130 // count the number of entries for a entity
2131 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2132 $params = [1 => [$entityId, 'Integer']];
2133 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2135 if ($count >= $maxMultiple) {
2136 $hasReachedMax = TRUE;
2140 return $hasReachedMax;
2146 public static function getMultipleFieldGroup() {
2147 $multipleGroup = [];
2148 $dao = new CRM_Core_DAO_CustomGroup();
2149 $dao->is_multiple
= 1;
2150 $dao->is_active
= 1;
2152 while ($dao->fetch()) {
2153 $multipleGroup[$dao->id
] = $dao->title
;
2155 return $multipleGroup;
2159 * Build the metadata tree for the custom group.
2161 * @param string $entityType
2162 * @param array $toReturn
2163 * @param array $subTypes
2164 * @param string $queryString
2165 * @param array $params
2166 * @param string $subType
2169 * @throws \CRM_Core_Exception
2171 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2172 $groupTree = $multipleFieldGroups = [];
2173 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
2174 $customValueTables = [];
2177 while ($crmDAO->fetch()) {
2179 $groupID = $crmDAO->civicrm_custom_group_id
;
2180 $fieldId = $crmDAO->civicrm_custom_field_id
;
2181 if ($crmDAO->civicrm_custom_group_is_multiple
) {
2182 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
2184 // create an array for groups if it does not exist
2185 if (!array_key_exists($groupID, $groupTree)) {
2186 $groupTree[$groupID] = [];
2187 $groupTree[$groupID]['id'] = $groupID;
2189 // populate the group information
2190 foreach ($toReturn['custom_group'] as $fieldName) {
2191 $fullFieldName = "civicrm_custom_group_$fieldName";
2192 if ($fieldName == 'id' ||
2193 is_null($crmDAO->$fullFieldName)
2198 // This is an old bit of code - per the CRM number & probably does not work reliably if
2199 // that one contact sub-type exists.
2200 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2201 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
2203 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2205 $groupTree[$groupID]['fields'] = [];
2207 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = [];
2210 // add the fields now (note - the query row will always contain a field)
2211 // we only reset this once, since multiple values come is as multiple rows
2212 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2213 $groupTree[$groupID]['fields'][$fieldId] = [];
2216 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
2217 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2218 // populate information for a custom field
2219 foreach ($toReturn['custom_field'] as $fieldName) {
2220 $fullFieldName = "civicrm_custom_field_$fieldName";
2221 if ($fieldName == 'id' ||
2222 is_null($crmDAO->$fullFieldName)
2226 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2230 if (!empty($customValueTables)) {
2231 $groupTree['info'] = ['tables' => $customValueTables];
2233 return [$multipleFieldGroups, $groupTree];