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 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
265 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
268 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
272 * Determine if given entity (sub)type has any custom groups
274 * @param string $extends
275 * E.g. "Individual", "Activity".
276 * @param int $columnId
277 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
278 * @param string $columnValue
279 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
283 public static function hasCustomGroup($extends, $columnId, $columnValue) {
284 $dao = new CRM_Core_DAO_CustomGroup();
285 $dao->extends = $extends;
286 $dao->extends_entity_column_id
= $columnId;
287 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
288 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
289 //$dao->extends_entity_column_value = $columnValue;
290 return $dao->find() ?
TRUE : FALSE;
294 * Determine if there are any CustomGroups for the given $activityTypeId.
295 * If none found, create one.
297 * @param int $activityTypeId
300 * TRUE if a group is found or created; FALSE on error
302 public static function autoCreateByActivityType($activityTypeId) {
303 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
307 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
310 'extends' => 'Activity',
311 'extends_entity_column_id' => NULL,
312 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded([$activityTypeId]),
313 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
317 $result = civicrm_api('CustomGroup', 'create', $params);
318 return !$result['is_error'];
322 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
323 * This may also include entity specific data values.
325 * An array containing all custom groups and their custom fields is returned.
327 * @param string $entityType
328 * Of the contact whose contact type is needed.
329 * @param array $toReturn
330 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
331 * @param int $entityID
332 * @param int $groupID
333 * @param array $subTypes
334 * @param string $subName
335 * @param bool $fromCache
336 * @param bool $onlySubType
337 * Only return specified subtype or return specified subtype + unrestricted fields.
338 * @param bool $returnAll
339 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
340 * api - through which it is properly tested - so can be refactored with some comfort.)
342 * @param bool $checkPermission
343 * @param string|int $singleRecord
344 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
345 * @param bool $showPublicOnly
348 * Custom field 'tree'.
350 * The returned array is keyed by group id and has the custom group table fields
351 * and a subkey 'fields' holding the specific custom fields.
352 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
353 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
355 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
356 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
357 * With caching the performance impact would be small & the function would be cleaner
359 * @throws \CRM_Core_Exception
361 public static function getTree(
371 $checkPermission = TRUE,
372 $singleRecord = NULL,
373 $showPublicOnly = FALSE
376 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
378 if (!is_array($subTypes)) {
379 if (empty($subTypes)) {
383 if (stristr($subTypes, ',')) {
384 $subTypes = explode(',', $subTypes);
387 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
394 // legacy hardcoded list of data to return
428 'extends_entity_column_id',
429 'extends_entity_column_value',
433 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
434 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
435 if ($is_public_version) {
436 $tableData['custom_group'][] = 'is_public';
438 if (!$toReturn ||
!is_array($toReturn)) {
439 $toReturn = $tableData;
442 // Supply defaults and remove unknown array keys
443 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
444 // Merge in required fields that we must have
445 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
446 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
447 // Validate return fields
448 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
449 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
454 foreach ($toReturn as $tableName => $tableColumn) {
455 foreach ($tableColumn as $columnName) {
456 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
459 $strSelect = "SELECT " . implode(', ', $select);
461 // from, where, order by
463 FROM civicrm_custom_group
464 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
467 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
468 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
469 $entityType == 'Household'
471 $in = "'$entityType', 'Contact'";
473 elseif (strpos($entityType, "'") !== FALSE) {
474 // this allows the calling function to send in multiple entity types
479 $in = "'$entityType'";
484 if (!empty($subTypes)) {
485 foreach ($subTypes as $key => $subType) {
486 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
488 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
490 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
494 WHERE civicrm_custom_group.is_active = 1
495 AND civicrm_custom_field.is_active = 1
496 AND civicrm_custom_group.extends IN ($in)
500 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
501 $params[$sqlParamKey] = [$subName, 'String'];
502 $sqlParamKey = $sqlParamKey +
1;
507 WHERE civicrm_custom_group.is_active = 1
508 AND civicrm_custom_field.is_active = 1
509 AND civicrm_custom_group.extends IN ($in)
512 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
517 // since we want a specific group id we add it to the where clause
518 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
519 $params[$sqlParamKey] = [$groupID, 'Integer'];
522 // since groupID is false we need to show all Inline groups
523 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
525 if ($checkPermission) {
526 // ensure that the user has access to these custom groups
527 $strWhere .= " AND " .
528 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
529 'civicrm_custom_group.'
533 if ($showPublicOnly && $is_public_version) {
534 $strWhere .= "AND civicrm_custom_group.is_public = 1";
538 ORDER BY civicrm_custom_group.weight,
539 civicrm_custom_group.title,
540 civicrm_custom_field.weight,
541 civicrm_custom_field.label
544 // final query string
545 $queryString = "$strSelect $strFrom $strWhere $orderBy";
547 // lets see if we can retrieve the groupTree from cache
548 $cacheString = $queryString;
550 $cacheString .= "_{$groupID}";
553 $cacheString .= "_Inline";
556 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
557 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
558 $cache = CRM_Utils_Cache
::singleton();
560 $groupTree = $cache->get($cacheKey);
561 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
564 if (empty($groupTree)) {
565 $groupTree = $multipleFieldGroups = [];
566 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
567 $customValueTables = [];
570 while ($crmDAO->fetch()) {
572 $groupID = $crmDAO->civicrm_custom_group_id
;
573 $fieldId = $crmDAO->civicrm_custom_field_id
;
574 if ($crmDAO->civicrm_custom_group_is_multiple
) {
575 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
577 // create an array for groups if it does not exist
578 if (!array_key_exists($groupID, $groupTree)) {
579 $groupTree[$groupID] = [];
580 $groupTree[$groupID]['id'] = $groupID;
582 // populate the group information
583 foreach ($toReturn['custom_group'] as $fieldName) {
584 $fullFieldName = "civicrm_custom_group_$fieldName";
585 if ($fieldName == 'id' ||
586 is_null($crmDAO->$fullFieldName)
591 // This is an old bit of code - per the CRM number & probably does not work reliably if
592 // that one contact sub-type exists.
593 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
594 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
596 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
598 $groupTree[$groupID]['fields'] = [];
600 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = [];
603 // add the fields now (note - the query row will always contain a field)
604 // we only reset this once, since multiple values come is as multiple rows
605 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
606 $groupTree[$groupID]['fields'][$fieldId] = [];
609 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
610 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
611 // populate information for a custom field
612 foreach ($toReturn['custom_field'] as $fieldName) {
613 $fullFieldName = "civicrm_custom_field_$fieldName";
614 if ($fieldName == 'id' ||
615 is_null($crmDAO->$fullFieldName)
619 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
623 if (!empty($customValueTables)) {
624 $groupTree['info'] = ['tables' => $customValueTables];
627 $cache->set($cacheKey, $groupTree);
628 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
630 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
631 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
632 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
633 $singleFieldTables = [];
634 // now that we have all the groups and fields, lets get the values
635 // since we need to know the table and field names
636 // add info to groupTree
638 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
639 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
641 $select = $from = $where = [];
642 $groupTree['info']['where'] = NULL;
644 foreach ($groupTree['info']['tables'] as $table => $fields) {
645 $groupTree['info']['from'][] = $table;
647 "{$table}.id as {$table}_id",
648 "{$table}.entity_id as {$table}_entity_id",
650 foreach ($fields as $column => $dontCare) {
651 $select[] = "{$table}.{$column} as {$table}_{$column}";
653 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
655 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
656 if (in_array($table, $multipleFieldGroups) &&
657 self
::customGroupDataExistsForEntity($entityID, $table)
659 $entityMultipleSelectClauses[$table] = $select;
662 $singleFieldTables[] = $table;
663 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
668 if ($entityID && !empty($singleFieldTables)) {
669 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
671 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
672 if (!empty($multipleFieldTablesWithEntityData)) {
673 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
681 * Clean and validate the filter before it is used in a db query.
683 * @param string $entityType
684 * @param string $subType
687 * @throws \CRM_Core_Exception
689 protected static function validateSubTypeByEntity($entityType, $subType) {
690 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
691 if (is_numeric($subType)) {
695 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
696 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
698 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
699 throw new CRM_Core_Exception('Invalid Entity Filter');
701 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
702 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
703 if (!array_key_exists($subType, $subTypes)) {
704 throw new CRM_Core_Exception('Invalid Filter');
710 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
711 * a WHERE condition for rows that include $value. Use whereListHas().
713 * @param string $column
714 * @param string $value
715 * @param string $delimiter
719 static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
721 $bareValue = trim($value, $delimiter);
722 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
723 return "($column LIKE \"$escapedValue\")";
727 * Check whether the custom group has any data for the given entity.
729 * @param int $entityID
730 * Id of entity for whom we are checking data for.
731 * @param string $table
732 * Table that we are checking.
734 * @param bool $getCount
737 * does this entity have data in this custom table
739 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
743 WHERE entity_id = $entityID
745 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
747 return $recordExists;
749 return $recordExists ?
TRUE : FALSE;
753 * Build the group tree for Custom fields which are not 'is_multiple'
755 * The combination of all these fields in one query with a 'using' join was not working for
756 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
757 * mechanism as it seemed to be acceptable in this context
759 * @param array $groupTree
760 * (reference) group tree array which is being built.
761 * @param int $entityID
762 * Id of entity for whom the tree is being build up.
763 * @param array $entitySingleSelectClauses
764 * Array of select clauses relevant to the entity.
765 * @param array $singleFieldTablesWithEntityData
766 * Array of tables in which this entity has data.
768 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
769 $select = implode(', ', $entitySingleSelectClauses);
770 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
771 foreach ($singleFieldTablesWithEntityData as $table) {
772 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
778 WHERE first.entity_id = $entityID
780 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
784 * Build the group tree for Custom fields which are 'is_multiple'
786 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
788 * @param array $groupTree
789 * (reference) group tree array which is being built.
790 * @param int $entityID
791 * Id of entity for whom the tree is being build up.
792 * @param array $entityMultipleSelectClauses
793 * Array of select clauses relevant to the entity.
794 * @param array $multipleFieldTablesWithEntityData
795 * Array of tables in which this entity has data.
796 * @param string|int $singleRecord
797 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
799 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
800 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
801 $select = implode(',', $selectClauses);
805 WHERE entity_id = $entityID
808 $offset = $singleRecord - 1;
809 $query .= " LIMIT {$offset}, 1";
811 self
::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
816 * Build the tree entity data - starting from a query retrieving the custom fields build the group
817 * tree data for the relevant entity (entity is included in the query).
819 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
821 * @param array $groupTree
822 * (reference) group tree array which is being built.
823 * @param string $query
824 * @param array $includedTables
825 * Tables to include - required because the function (for historical reasons).
826 * iterates through the group tree
827 * @param string|int $singleRecord
828 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
830 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
831 $dao = CRM_Core_DAO
::executeQuery($query);
832 while ($dao->fetch()) {
833 foreach ($groupTree as $groupID => $group) {
834 if ($groupID === 'info') {
837 $table = $groupTree[$groupID]['table_name'];
838 //working from the groupTree instead of the table list means we have to iterate & exclude.
839 // this could possibly be re-written as other parts of the function have been refactored
840 // for now we just check if the given table is to be included in this function
841 if (!in_array($table, $includedTables)) {
844 foreach ($group['fields'] as $fieldID => $dontCare) {
845 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
852 * Build the entity-specific custom data into the group tree on a per-field basis
855 * Object representing the custom field to be populated into the groupTree.
856 * @param array $groupTree
857 * (reference) the group tree being build.
858 * @param string $table
860 * @param int $groupID
862 * @param int $fieldID
864 * @param string|int $singleRecord
865 * holds 'new' or id if loading view/edit/copy for a single record.
867 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
868 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
869 $idName = "{$table}_id";
870 $fieldName = "{$table}_{$column}";
871 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
872 if ($dataType == 'File') {
873 if (isset($dao->$fieldName)) {
874 $config = CRM_Core_Config
::singleton();
875 $fileDAO = new CRM_Core_DAO_File();
876 $fileDAO->id
= $dao->$fieldName;
878 if ($fileDAO->find(TRUE)) {
879 $entityIDName = "{$table}_entity_id";
880 $fileHash = CRM_Core_BAO_File
::generateFileHash($dao->$entityIDName, $fileDAO->id
);
881 $customValue['id'] = $dao->$idName;
882 $customValue['data'] = $fileDAO->uri
;
883 $customValue['fid'] = $fileDAO->id
;
884 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
885 $customValue['displayURL'] = NULL;
886 $deleteExtra = ts('Are you sure you want to delete attached file.');
888 CRM_Core_Action
::DELETE
=> [
889 'name' => ts('Delete Attached File'),
890 'url' => 'civicrm/file',
891 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
892 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
893 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
896 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
897 CRM_Core_Action
::DELETE
,
899 'id' => $fileDAO->id
,
900 'eid' => $dao->$entityIDName,
906 'file.manage.delete',
910 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
911 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
912 if ($fileDAO->mime_type
== "image/jpeg" ||
913 $fileDAO->mime_type
== "image/pjpeg" ||
914 $fileDAO->mime_type
== "image/gif" ||
915 $fileDAO->mime_type
== "image/x-png" ||
916 $fileDAO->mime_type
== "image/png"
918 $customValue['displayURL'] = $customValue['fileURL'];
919 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
924 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
926 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId);
927 if ($path && file_exists($path)) {
928 list($imageWidth, $imageHeight) = getimagesize($path);
929 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
930 $customValue['imageThumbWidth'] = $imageThumbWidth;
931 $customValue['imageThumbHeight'] = $imageThumbHeight;
938 'id' => $dao->$idName,
945 'id' => $dao->$idName,
946 'data' => $dao->$fieldName,
950 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
951 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
953 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
954 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
956 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
957 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
960 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
965 * Get the group title.
973 public static function getTitle($id) {
974 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
978 * Get custom group details for a group.
980 * An array containing custom group details (including their custom field) is returned.
982 * @param int $groupId
983 * Group id whose details are needed.
984 * @param bool $searchable
985 * Is this field searchable.
986 * @param array $extends
987 * Which table does it extend if any.
989 * @param bool $inSelector
992 * array consisting of all group and field details
994 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
998 // using tableData to build the queryString
1000 'civicrm_custom_field' => [
1024 'civicrm_custom_group' => [
1031 'collapse_adv_display',
1033 'extends_entity_column_value',
1041 foreach ($tableData as $tableName => $tableColumn) {
1042 foreach ($tableColumn as $columnName) {
1043 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
1046 $select = 'SELECT ' . implode(', ', $s);
1048 // from, where, order by
1049 $from = " FROM civicrm_custom_field, civicrm_custom_group";
1050 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
1051 AND civicrm_custom_group.is_active = 1
1052 AND civicrm_custom_field.is_active = 1 ";
1054 $params[1] = [$groupId, 'Integer'];
1055 $where .= " AND civicrm_custom_group.id = %1";
1059 $where .= " AND civicrm_custom_field.is_searchable = 1";
1063 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1068 foreach ($extends as $e) {
1069 $clause[] = "civicrm_custom_group.extends = '$e'";
1071 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1073 //include case activities customdata if case is enabled
1074 if (in_array('Activity', $extends)) {
1075 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1076 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1077 $params[2] = [CRM_Core_DAO
::VALUE_SEPARATOR
, 'String'];
1081 // ensure that the user has access to these custom groups
1083 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1084 'civicrm_custom_group.'
1087 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1089 // final query string
1090 $queryString = $select . $from . $where . $orderBy;
1093 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1096 while ($crmDAO->fetch()) {
1097 $groupId = $crmDAO->civicrm_custom_group_id
;
1098 $fieldId = $crmDAO->civicrm_custom_field_id
;
1100 // create an array for groups if it does not exist
1101 if (!array_key_exists($groupId, $groupTree)) {
1102 $groupTree[$groupId] = [];
1103 $groupTree[$groupId]['id'] = $groupId;
1105 foreach ($tableData['civicrm_custom_group'] as $v) {
1106 $fullField = "civicrm_custom_group_" . $v;
1108 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1112 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1115 $groupTree[$groupId]['fields'] = [];
1118 // add the fields now (note - the query row will always contain a field)
1119 $groupTree[$groupId]['fields'][$fieldId] = [];
1120 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1122 foreach ($tableData['civicrm_custom_field'] as $v) {
1123 $fullField = "civicrm_custom_field_" . $v;
1124 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1127 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1135 * @param $entityType
1137 * @param string $cidToken
1141 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1143 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1145 // get 'Tab' and 'Tab with table' groups
1146 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1147 $customGroupDAO->whereAdd("is_active = 1");
1149 // add whereAdd for entity type
1150 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1154 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1155 $customGroupDAO->whereAdd($permissionClause);
1158 $customGroupDAO->orderBy('weight');
1159 $customGroupDAO->find();
1161 // process each group with menu tab
1162 while ($customGroupDAO->fetch()) {
1164 $group['id'] = $customGroupDAO->id
;
1165 $group['path'] = $path;
1166 $group['title'] = "$customGroupDAO->title";
1167 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1168 $group['extra'] = ['gid' => $customGroupDAO->id
];
1169 $group['table_name'] = $customGroupDAO->table_name
;
1170 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1178 * Get the table name for the entity type
1179 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1180 * tableName is 'civicrm_contact'
1182 * @param string $entityType
1183 * What entity are we extending here ?.
1188 * @see _apachesolr_civiAttachments_dereference_file_parent
1190 public static function getTableNameByEntityName($entityType) {
1192 switch ($entityType) {
1196 case 'Organization':
1197 $tableName = 'civicrm_contact';
1200 case 'Contribution':
1201 $tableName = 'civicrm_contribution';
1205 $tableName = 'civicrm_group';
1208 // DRAFTING: Verify if we cannot make it pluggable
1211 $tableName = 'civicrm_activity';
1214 case 'Relationship':
1215 $tableName = 'civicrm_relationship';
1219 $tableName = 'civicrm_membership';
1223 $tableName = 'civicrm_participant';
1227 $tableName = 'civicrm_event';
1231 $tableName = 'civicrm_grant';
1234 // need to add cases for Location, Address
1241 * Get a list of custom groups which extend a given entity type.
1242 * If there are custom-groups which only apply to certain subtypes,
1243 * those WILL be included.
1245 * @param string $entityType
1247 * @return CRM_Core_DAO_CustomGroup
1249 public static function getAllCustomGroupsByBaseEntity($entityType) {
1250 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1251 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1252 return $customGroupDAO;
1256 * Add the whereAdd clause for the DAO depending on the type of entity
1257 * the custom group is extending.
1259 * @param object $customGroupDAO
1260 * @param string $entityType
1261 * What entity are we extending here ?.
1263 * @param int $entityID
1264 * @param bool $allSubtypes
1266 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1267 $addSubtypeClause = FALSE;
1268 // This function isn't really accessible with user data but since the string
1269 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1271 $entityType = CRM_Core_DAO
::escapeString($entityType);
1273 switch ($entityType) {
1275 // if contact, get all related to contact
1276 $extendList = "'Contact','Individual','Household','Organization'";
1277 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1278 if (!$allSubtypes) {
1279 $addSubtypeClause = TRUE;
1285 case 'Organization':
1286 // is I/H/O then get I/H/O and contact
1287 $extendList = "'Contact','$entityType'";
1288 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1289 if (!$allSubtypes) {
1290 $addSubtypeClause = TRUE;
1295 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1299 if ($addSubtypeClause) {
1300 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1302 if (!empty($csType)) {
1303 $subtypeClause = [];
1304 foreach ($csType as $subtype) {
1305 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1306 CRM_Core_DAO
::VALUE_SEPARATOR
;
1307 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1309 $subtypeClause[] = "extends_entity_column_value IS NULL";
1310 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1314 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1320 * Delete the Custom Group.
1322 * @param CRM_Core_BAO_CustomGroup $group
1323 * Custom group object.
1324 * @param bool $force
1325 * whether to force the deletion, even if there are custom fields.
1328 * False if field exists for this group, true if group gets deleted.
1330 public static function deleteGroup($group, $force = FALSE) {
1332 //check whether this contain any custom fields
1333 $customField = new CRM_Core_DAO_CustomField();
1334 $customField->custom_group_id
= $group->id
;
1335 $customField->find();
1337 // return early if there are custom fields and we're not
1338 // forcing the delete, otherwise delete the fields one by one
1339 while ($customField->fetch()) {
1343 CRM_Core_BAO_CustomField
::deleteField($customField);
1346 // drop the table associated with this custom group
1347 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1349 //delete custom group
1352 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1360 * @param array $groupTree
1361 * @param array $defaults
1362 * @param bool $viewMode
1363 * @param bool $inactiveNeeded
1364 * @param int $action
1366 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1367 foreach ($groupTree as $id => $group) {
1368 if (!isset($group['fields'])) {
1371 foreach ($group['fields'] as $field) {
1372 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1373 $value = $field['element_value'];
1375 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1376 ($action != CRM_Core_Action
::UPDATE ||
1378 !array_key_exists('element_value', $field)
1381 $value = $viewMode ?
NULL : $field['default_value'];
1387 if (empty($field['element_name'])) {
1391 $elementName = $field['element_name'];
1393 switch ($field['html_type']) {
1394 case 'Multi-Select':
1396 $defaults[$elementName] = [];
1397 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1399 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1400 if (isset($value)) {
1401 foreach ($customOption as $customValue => $customLabel) {
1402 if (in_array($customValue, $checkedData)) {
1403 if ($field['html_type'] == 'CheckBox') {
1404 $defaults[$elementName][$customValue] = 1;
1407 $defaults[$elementName][$customValue] = $customValue;
1411 $defaults[$elementName][$customValue] = 0;
1417 if (isset($field['customValue']['data'])) {
1418 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1419 foreach ($customOption as $val) {
1420 if (in_array($val['value'], $checkedData)) {
1421 if ($field['html_type'] == 'CheckBox') {
1422 $defaults[$elementName][$val['value']] = 1;
1425 $defaults[$elementName][$val['value']] = $val['value'];
1429 $defaults[$elementName][$val['value']] = 0;
1434 if (is_array($value) && count($value)) {
1435 CRM_Utils_Array
::formatArrayKeys($value);
1436 $checkedValue = $value;
1439 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1441 foreach ($customOption as $val) {
1442 if (in_array($val['value'], $checkedValue)) {
1443 if ($field['html_type'] == 'CheckBox') {
1444 $defaults[$elementName][$val['value']] = 1;
1447 $defaults[$elementName][$val['value']] = $val['value'];
1455 case 'Multi-Select Country':
1456 case 'Multi-Select State/Province':
1457 if (isset($value)) {
1458 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1459 foreach ($checkedValue as $val) {
1461 $defaults[$elementName][$val] = $val;
1467 case 'Select Country':
1469 $defaults[$elementName] = $value;
1472 $config = CRM_Core_Config
::singleton();
1473 $defaults[$elementName] = $config->defaultContactCountry
;
1478 if ($field['data_type'] == "Float") {
1479 $defaults[$elementName] = (float) $value;
1481 elseif ($field['data_type'] == 'Money' &&
1482 $field['html_type'] == 'Text'
1484 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1487 $defaults[$elementName] = $value;
1495 * PostProcess function.
1497 * @param array $groupTree
1498 * @param array $params
1499 * @param bool $skipFile
1501 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1502 // Get the Custom form values and groupTree
1503 // first reset all checkbox and radio data
1504 foreach ($groupTree as $groupID => $group) {
1505 if ($groupID === 'info') {
1508 foreach ($group['fields'] as $field) {
1509 $fieldId = $field['id'];
1511 //added Multi-Select option in the below if-statement
1512 if ($field['html_type'] == 'CheckBox' ||
1513 $field['html_type'] == 'Radio' ||
1514 $field['html_type'] == 'Multi-Select'
1516 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1520 foreach ($params as $key => $val) {
1521 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1522 $match[1] == $field['id']
1528 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1529 // field exists in db so populate value from "form".
1530 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
1533 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1535 // added for CheckBox
1538 $customValue = array_keys($v);
1539 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1540 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1541 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1544 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1548 case 'Multi-Select':
1550 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1551 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1552 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1555 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1560 $date = CRM_Utils_Date
::processDate($v);
1561 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1569 // store the file in d/b
1570 $entityId = explode('=', $groupTree['info']['where'][0]);
1571 $fileParams = ['upload_date' => date('YmdHis')];
1573 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1574 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1577 $fileParams['uri'] = $v['name'];
1578 $fileParams['mime_type'] = $v['type'];
1579 CRM_Core_BAO_File
::filePostProcess($v['name'],
1580 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1581 $groupTree[$groupID]['table_name'],
1586 'custom_' . $fieldId,
1592 'entity_table' => $groupTree[$groupID]['table_name'],
1593 'entity_id' => $entityId[1],
1596 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1601 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1605 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1613 * Generic function to build all the form elements for a specific group tree.
1615 * @param CRM_Core_Form $form
1617 * @param array $groupTree
1618 * The group tree object.
1619 * @param bool $inactiveNeeded
1620 * Return inactive custom groups.
1621 * @param string $prefix
1622 * Prefix for custom grouptree assigned to template.
1624 * @throws \CiviCRM_API3_Exception
1626 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1627 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1629 foreach ($groupTree as $id => $group) {
1630 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1631 foreach ($group['fields'] as $field) {
1632 $required = CRM_Utils_Array
::value('is_required', $field);
1634 if ($field['data_type'] == 'File') {
1635 if (!empty($field['element_value']['data'])) {
1640 $fieldId = $field['id'];
1641 $elementName = $field['element_name'];
1642 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1643 if ($form->getAction() == CRM_Core_Action
::VIEW
) {
1644 $form->getElement($elementName)->freeze();
1651 * Extract the get params from the url, validate and store it in session.
1653 * @param CRM_Core_Form $form
1655 * @param string $type
1656 * The type of custom group we are using.
1659 * @throws \CRM_Core_Exception
1660 * @throws \CiviCRM_API3_Exception
1662 public static function extractGetParams(&$form, $type) {
1667 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1676 foreach ($groupTree as $group) {
1677 if (!isset($group['fields'])) {
1680 foreach ($group['fields'] as $key => $field) {
1681 $fieldName = 'custom_' . $key;
1682 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1686 if (!in_array($field['html_type'], $htmlType) ||
1687 $field['data_type'] == 'Boolean'
1689 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1691 if ($field['html_type'] == 'CheckBox' ||
1692 $field['html_type'] == 'Multi-Select'
1694 $value = str_replace("|", ",", $value);
1695 $mulValues = explode(',', $value);
1696 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1698 foreach ($mulValues as $v1) {
1699 foreach ($customOption as $coID => $coValue) {
1700 if (strtolower(trim($coValue['label'])) ==
1701 strtolower(trim($v1))
1703 $val[$coValue['value']] = 1;
1715 elseif ($field['html_type'] == 'Select' ||
1716 ($field['html_type'] == 'Radio' &&
1717 $field['data_type'] != 'Boolean'
1720 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1721 foreach ($customOption as $customID => $coValue) {
1722 if (strtolower(trim($coValue['label'])) ==
1723 strtolower(trim($value))
1725 $value = $coValue['value'];
1730 elseif ($field['data_type'] == 'Date') {
1731 $valid = CRM_Utils_Rule
::date($value);
1735 $customValue[$fieldName] = $value;
1741 return $customValue;
1745 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1746 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1748 * @param int $customFieldId
1750 * @param array $removeCustomFieldTypes
1751 * Remove custom fields of a type eg: array("Individual") ;.
1754 * false if it matches else true
1756 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1757 $query = "SELECT cg.extends as extends
1758 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1759 WHERE cg.id = cf.custom_group_id
1761 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1763 $extends = CRM_Core_DAO
::singleValueQuery($query);
1765 if (in_array($extends, $removeCustomFieldTypes)) {
1777 public static function mapTableName($table) {
1782 case 'Organization':
1783 return 'civicrm_contact';
1786 return 'civicrm_activity';
1789 return 'civicrm_group';
1791 case 'Contribution':
1792 return 'civicrm_contribution';
1794 case 'ContributionRecur':
1795 return 'civicrm_contribution_recur';
1797 case 'Relationship':
1798 return 'civicrm_relationship';
1801 return 'civicrm_event';
1804 return 'civicrm_membership';
1807 case 'ParticipantRole':
1808 case 'ParticipantEventName':
1809 case 'ParticipantEventType':
1810 return 'civicrm_participant';
1813 return 'civicrm_grant';
1816 return 'civicrm_pledge';
1819 return 'civicrm_address';
1822 return 'civicrm_campaign';
1826 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1827 $qParams = [1 => [$table, 'String']];
1828 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1831 return 'civicrm_contact';
1834 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1835 if (array_key_exists($table, $extendObjs)) {
1836 return $extendObjs[$table];
1838 CRM_Core_Error
::fatal();
1846 * @throws \Exception
1848 public static function createTable($group) {
1850 'name' => $group->table_name
,
1851 'is_multiple' => $group->is_multiple ?
1 : 0,
1852 'extends_name' => self
::mapTableName($group->extends),
1855 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1857 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1861 * Function returns formatted groupTree, so that form can be easily built in template
1863 * @param array $groupTree
1864 * @param int $groupCount
1865 * Group count by default 1, but can vary for multiple value custom data.
1866 * @param \CRM_Core_Form $form
1869 * @throws \CRM_Core_Exception
1871 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1872 $formattedGroupTree = [];
1873 $uploadNames = $formValues = [];
1875 // retrieve qf key from url
1876 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1878 // fetch submitted custom field values later use to set as a default values
1880 $submittedValues = CRM_Core_BAO_Cache
::getItem('custom data', $qfKey);
1883 foreach ($groupTree as $key => $value) {
1884 if ($key === 'info') {
1888 // add group information
1889 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1890 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1891 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1892 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1893 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1894 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1895 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1897 // this params needed of bulding multiple values
1898 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1899 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1900 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1901 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1902 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1903 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1905 // add field information
1906 foreach ($value['fields'] as $k => $properties) {
1907 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1908 if (isset($properties['customValue']) &&
1909 !CRM_Utils_System
::isNull($properties['customValue']) &&
1910 !isset($properties['element_value'])
1912 if (isset($properties['customValue'][$groupCount])) {
1913 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1914 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1915 if ($properties['data_type'] == 'File') {
1916 $properties['element_value'] = $properties['customValue'][$groupCount];
1917 $uploadNames[] = $properties['element_name'];
1920 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1924 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1925 $formValues[$properties['element_name']] = $value;
1927 elseif (isset($submittedValues[$properties['element_name']])) {
1928 $properties['element_value'] = $submittedValues[$properties['element_name']];
1930 unset($properties['customValue']);
1931 $formattedGroupTree[$key]['fields'][$k] = $properties;
1936 if (count($formValues)) {
1937 $qf = $form->get('qfKey');
1938 $form->assign('qfKey', $qf);
1939 CRM_Core_BAO_Cache
::setItem($formValues, 'custom data', $qf);
1942 // hack for field type File
1943 $formUploadNames = $form->get('uploadNames');
1944 if (is_array($formUploadNames)) {
1945 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1948 $form->set('uploadNames', $uploadNames);
1951 return $formattedGroupTree;
1955 * Build custom data view.
1957 * @param CRM_Core_Form|CRM_Core_Page $form
1959 * @param array $groupTree
1960 * @param bool $returnCount
1961 * True if customValue count needs to be returned.
1963 * @param null $prefix
1964 * @param int $customValueId
1965 * @param int $entityId
1968 * @throws \Exception
1970 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1972 foreach ($groupTree as $key => $group) {
1973 if ($key === 'info') {
1977 foreach ($group['fields'] as $k => $properties) {
1978 $groupID = $group['id'];
1979 if (!empty($properties['customValue'])) {
1980 foreach ($properties['customValue'] as $values) {
1981 if (!empty($customValueId) && $customValueId != $values['id']) {
1984 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1985 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1986 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1987 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1988 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1989 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1990 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1991 $details[$groupID][$values['id']]['fields'][$k] = [
1992 'field_title' => CRM_Utils_Array
::value('label', $properties),
1993 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1994 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1995 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1996 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1998 // editable = whether this set contains any non-read-only fields
1999 if (!isset($details[$groupID][$values['id']]['editable'])) {
2000 $details[$groupID][$values['id']]['editable'] = FALSE;
2002 if (empty($properties['is_view'])) {
2003 $details[$groupID][$values['id']]['editable'] = TRUE;
2005 // also return contact reference contact id if user has view all or edit all contacts perm
2006 if ((CRM_Core_Permission
::check('view all contacts') ||
2007 CRM_Core_Permission
::check('edit all contacts'))
2009 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
2012 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
2017 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
2018 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
2019 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
2020 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
2021 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
2022 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
2023 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
2024 $details[$groupID][0]['fields'][$k] = ['field_title' => CRM_Utils_Array
::value('label', $properties)];
2030 // return a single value count if group id is passed to function
2031 // else return a groupId and count mapped array
2033 return count($details[$gID]);
2037 foreach ($details as $key => $value) {
2038 $countValue[$key] = count($details[$key]);
2044 $form->assign_by_ref("{$prefix}viewCustomData", $details);
2050 * Get the custom group titles by custom field ids.
2052 * @param array $fieldIds
2053 * Array of custom field ids.
2055 * @return array|NULL
2056 * array consisting of groups and fields labels with ids.
2058 public static function getGroupTitles($fieldIds) {
2059 if (!is_array($fieldIds) && empty($fieldIds)) {
2064 $fIds = "(" . implode(',', $fieldIds) . ")";
2067 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2068 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2069 FROM civicrm_custom_group, civicrm_custom_field
2070 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2071 AND civicrm_custom_field.id IN {$fIds}";
2073 $dao = CRM_Core_DAO
::executeQuery($query);
2074 while ($dao->fetch()) {
2075 $groupLabels[$dao->fieldID
] = [
2076 'fieldID' => $dao->fieldID
,
2077 'fieldLabel' => $dao->fieldLabel
,
2078 'groupID' => $dao->groupID
,
2079 'groupTitle' => $dao->groupTitle
,
2083 return $groupLabels;
2086 public static function dropAllTables() {
2087 $query = "SELECT table_name FROM civicrm_custom_group";
2088 $dao = CRM_Core_DAO
::executeQuery($query);
2090 while ($dao->fetch()) {
2091 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2092 CRM_Core_DAO
::executeQuery($query);
2097 * Check whether custom group is empty or not.
2103 * true if empty otherwise false.
2105 public static function isGroupEmpty($gID) {
2110 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2115 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2116 $value = CRM_Core_DAO
::singleValueQuery($query);
2118 if (empty($value)) {
2126 * Get the list of types for objects that a custom group extends to.
2128 * @param array $types
2129 * Var which should have the list appended.
2133 * @throws \Exception
2135 public static function getExtendedObjectTypes(&$types = []) {
2136 static $flag = FALSE, $objTypes = [];
2140 CRM_Core_OptionValue
::getValues(['name' => 'cg_extend_objects'], $extendObjs);
2142 foreach ($extendObjs as $ovId => $ovValues) {
2143 if ($ovValues['description']) {
2144 // description is expected to be a callback func to subtypes
2145 list($callback, $args) = explode(';', trim($ovValues['description']));
2151 if (!is_array($args)) {
2152 CRM_Core_Error
::fatal('Arg is not of type array');
2155 list($className) = explode('::', $callback);
2156 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
2158 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2164 $types = array_merge($types, $objTypes);
2169 * @param int $customGroupId
2170 * @param int $entityId
2174 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2175 // check whether the group is multiple
2176 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2177 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2178 $hasReachedMax = FALSE;
2180 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2182 if (!$maxMultiple) {
2183 $hasReachedMax = FALSE;
2186 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2187 // count the number of entries for a entity
2188 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2189 $params = [1 => [$entityId, 'Integer']];
2190 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2192 if ($count >= $maxMultiple) {
2193 $hasReachedMax = TRUE;
2197 return $hasReachedMax;
2203 public static function getMultipleFieldGroup() {
2204 $multipleGroup = [];
2205 $dao = new CRM_Core_DAO_CustomGroup();
2206 $dao->is_multiple
= 1;
2207 $dao->is_active
= 1;
2209 while ($dao->fetch()) {
2210 $multipleGroup[$dao->id
] = $dao->title
;
2212 return $multipleGroup;