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();
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'";
485 if (!empty($subTypes)) {
486 foreach ($subTypes as $key => $subType) {
487 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
489 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
491 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
495 WHERE civicrm_custom_group.is_active = 1
496 AND civicrm_custom_field.is_active = 1
497 AND civicrm_custom_group.extends IN ($in)
501 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
502 $params[$sqlParamKey] = [$subName, 'String'];
503 $sqlParamKey = $sqlParamKey +
1;
508 WHERE civicrm_custom_group.is_active = 1
509 AND civicrm_custom_field.is_active = 1
510 AND civicrm_custom_group.extends IN ($in)
513 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
518 // since we want a specific group id we add it to the where clause
519 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
520 $params[$sqlParamKey] = [$groupID, 'Integer'];
523 // since groupID is false we need to show all Inline groups
524 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
526 if ($checkPermission) {
527 // ensure that the user has access to these custom groups
528 $strWhere .= " AND " .
529 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
530 'civicrm_custom_group.'
534 if ($showPublicOnly && $is_public_version) {
535 $strWhere .= "AND civicrm_custom_group.is_public = 1";
539 ORDER BY civicrm_custom_group.weight,
540 civicrm_custom_group.title,
541 civicrm_custom_field.weight,
542 civicrm_custom_field.label
545 // final query string
546 $queryString = "$strSelect $strFrom $strWhere $orderBy";
548 // lets see if we can retrieve the groupTree from cache
549 $cacheString = $queryString;
551 $cacheString .= "_{$groupID}";
554 $cacheString .= "_Inline";
557 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
558 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
559 $cache = CRM_Utils_Cache
::singleton();
561 $groupTree = $cache->get($cacheKey);
562 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
565 if (empty($groupTree)) {
566 list($multipleFieldGroups, $groupTree) = self
::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType);
568 $cache->set($cacheKey, $groupTree);
569 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
571 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
572 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
573 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
574 $singleFieldTables = [];
575 // now that we have all the groups and fields, lets get the values
576 // since we need to know the table and field names
577 // add info to groupTree
579 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
580 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
582 $select = $from = $where = [];
583 $groupTree['info']['where'] = NULL;
585 foreach ($groupTree['info']['tables'] as $table => $fields) {
586 $groupTree['info']['from'][] = $table;
588 "{$table}.id as {$table}_id",
589 "{$table}.entity_id as {$table}_entity_id",
591 foreach ($fields as $column => $dontCare) {
592 $select[] = "{$table}.{$column} as {$table}_{$column}";
594 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
596 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
597 if (in_array($table, $multipleFieldGroups) &&
598 self
::customGroupDataExistsForEntity($entityID, $table)
600 $entityMultipleSelectClauses[$table] = $select;
603 $singleFieldTables[] = $table;
604 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
609 if ($entityID && !empty($singleFieldTables)) {
610 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
612 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
613 if (!empty($multipleFieldTablesWithEntityData)) {
614 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
622 * Clean and validate the filter before it is used in a db query.
624 * @param string $entityType
625 * @param string $subType
628 * @throws \CRM_Core_Exception
630 protected static function validateSubTypeByEntity($entityType, $subType) {
631 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
632 if (is_numeric($subType)) {
636 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
637 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
639 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
640 throw new CRM_Core_Exception('Invalid Entity Filter');
642 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
643 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
644 if (!array_key_exists($subType, $subTypes)) {
645 throw new CRM_Core_Exception('Invalid Filter');
651 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
652 * a WHERE condition for rows that include $value. Use whereListHas().
654 * @param string $column
655 * @param string $value
656 * @param string $delimiter
660 private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
662 $bareValue = trim($value, $delimiter);
663 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
664 return "($column LIKE \"$escapedValue\")";
668 * Check whether the custom group has any data for the given entity.
670 * @param int $entityID
671 * Id of entity for whom we are checking data for.
672 * @param string $table
673 * Table that we are checking.
675 * @param bool $getCount
678 * does this entity have data in this custom table
680 public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
684 WHERE entity_id = $entityID
686 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
688 return $recordExists;
690 return $recordExists ?
TRUE : FALSE;
694 * Build the group tree for Custom fields which are not 'is_multiple'
696 * The combination of all these fields in one query with a 'using' join was not working for
697 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
698 * mechanism as it seemed to be acceptable in this context
700 * @param array $groupTree
701 * (reference) group tree array which is being built.
702 * @param int $entityID
703 * Id of entity for whom the tree is being build up.
704 * @param array $entitySingleSelectClauses
705 * Array of select clauses relevant to the entity.
706 * @param array $singleFieldTablesWithEntityData
707 * Array of tables in which this entity has data.
709 public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
710 $select = implode(', ', $entitySingleSelectClauses);
711 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
712 foreach ($singleFieldTablesWithEntityData as $table) {
713 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
719 WHERE first.entity_id = $entityID
721 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
725 * Build the group tree for Custom fields which are 'is_multiple'
727 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
729 * @param array $groupTree
730 * (reference) group tree array which is being built.
731 * @param int $entityID
732 * Id of entity for whom the tree is being build up.
733 * @param array $entityMultipleSelectClauses
734 * Array of select clauses relevant to the entity.
735 * @param array $multipleFieldTablesWithEntityData
736 * Array of tables in which this entity has data.
737 * @param string|int $singleRecord
738 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
740 public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
741 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
742 $select = implode(',', $selectClauses);
746 WHERE entity_id = $entityID
749 $offset = $singleRecord - 1;
750 $query .= " LIMIT {$offset}, 1";
752 self
::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
757 * Build the tree entity data - starting from a query retrieving the custom fields build the group
758 * tree data for the relevant entity (entity is included in the query).
760 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
762 * @param array $groupTree
763 * (reference) group tree array which is being built.
764 * @param string $query
765 * @param array $includedTables
766 * Tables to include - required because the function (for historical reasons).
767 * iterates through the group tree
768 * @param string|int $singleRecord
769 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
771 public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
772 $dao = CRM_Core_DAO
::executeQuery($query);
773 while ($dao->fetch()) {
774 foreach ($groupTree as $groupID => $group) {
775 if ($groupID === 'info') {
778 $table = $groupTree[$groupID]['table_name'];
779 //working from the groupTree instead of the table list means we have to iterate & exclude.
780 // this could possibly be re-written as other parts of the function have been refactored
781 // for now we just check if the given table is to be included in this function
782 if (!in_array($table, $includedTables)) {
785 foreach ($group['fields'] as $fieldID => $dontCare) {
786 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
793 * Build the entity-specific custom data into the group tree on a per-field basis
796 * Object representing the custom field to be populated into the groupTree.
797 * @param array $groupTree
798 * (reference) the group tree being build.
799 * @param string $table
801 * @param int $groupID
803 * @param int $fieldID
805 * @param string|int $singleRecord
806 * holds 'new' or id if loading view/edit/copy for a single record.
808 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
809 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
810 $idName = "{$table}_id";
811 $fieldName = "{$table}_{$column}";
812 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
813 if ($dataType == 'File') {
814 if (isset($dao->$fieldName)) {
815 $config = CRM_Core_Config
::singleton();
816 $fileDAO = new CRM_Core_DAO_File();
817 $fileDAO->id
= $dao->$fieldName;
819 if ($fileDAO->find(TRUE)) {
820 $entityIDName = "{$table}_entity_id";
821 $fileHash = CRM_Core_BAO_File
::generateFileHash($dao->$entityIDName, $fileDAO->id
);
822 $customValue['id'] = $dao->$idName;
823 $customValue['data'] = $fileDAO->uri
;
824 $customValue['fid'] = $fileDAO->id
;
825 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
826 $customValue['displayURL'] = NULL;
827 $deleteExtra = ts('Are you sure you want to delete attached file.');
829 CRM_Core_Action
::DELETE
=> [
830 'name' => ts('Delete Attached File'),
831 'url' => 'civicrm/file',
832 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
833 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
834 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
837 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
838 CRM_Core_Action
::DELETE
,
840 'id' => $fileDAO->id
,
841 'eid' => $dao->$entityIDName,
847 'file.manage.delete',
851 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
852 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
853 if ($fileDAO->mime_type
== "image/jpeg" ||
854 $fileDAO->mime_type
== "image/pjpeg" ||
855 $fileDAO->mime_type
== "image/gif" ||
856 $fileDAO->mime_type
== "image/x-png" ||
857 $fileDAO->mime_type
== "image/png"
859 $customValue['displayURL'] = $customValue['fileURL'];
860 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
865 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
867 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId);
868 if ($path && file_exists($path)) {
869 list($imageWidth, $imageHeight) = getimagesize($path);
870 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
871 $customValue['imageThumbWidth'] = $imageThumbWidth;
872 $customValue['imageThumbHeight'] = $imageThumbHeight;
879 'id' => $dao->$idName,
886 'id' => $dao->$idName,
887 'data' => $dao->$fieldName,
891 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
892 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
894 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
895 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
897 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
898 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
901 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
906 * Get the group title.
914 public static function getTitle($id) {
915 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
919 * Get custom group details for a group.
921 * An array containing custom group details (including their custom field) is returned.
923 * @param int $groupId
924 * Group id whose details are needed.
925 * @param bool $searchable
926 * Is this field searchable.
927 * @param array $extends
928 * Which table does it extend if any.
930 * @param bool $inSelector
933 * array consisting of all group and field details
935 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
939 // using tableData to build the queryString
941 'civicrm_custom_field' => [
965 'civicrm_custom_group' => [
972 'collapse_adv_display',
974 'extends_entity_column_value',
982 foreach ($tableData as $tableName => $tableColumn) {
983 foreach ($tableColumn as $columnName) {
984 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
987 $select = 'SELECT ' . implode(', ', $s);
989 // from, where, order by
990 $from = " FROM civicrm_custom_field, civicrm_custom_group";
991 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
992 AND civicrm_custom_group.is_active = 1
993 AND civicrm_custom_field.is_active = 1 ";
995 $params[1] = [$groupId, 'Integer'];
996 $where .= " AND civicrm_custom_group.id = %1";
1000 $where .= " AND civicrm_custom_field.is_searchable = 1";
1004 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1009 foreach ($extends as $e) {
1010 $clause[] = "civicrm_custom_group.extends = '$e'";
1012 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1014 //include case activities customdata if case is enabled
1015 if (in_array('Activity', $extends)) {
1016 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1017 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1018 $params[2] = [CRM_Core_DAO
::VALUE_SEPARATOR
, 'String'];
1022 // ensure that the user has access to these custom groups
1024 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1025 'civicrm_custom_group.'
1028 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1030 // final query string
1031 $queryString = $select . $from . $where . $orderBy;
1034 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1037 while ($crmDAO->fetch()) {
1038 $groupId = $crmDAO->civicrm_custom_group_id
;
1039 $fieldId = $crmDAO->civicrm_custom_field_id
;
1041 // create an array for groups if it does not exist
1042 if (!array_key_exists($groupId, $groupTree)) {
1043 $groupTree[$groupId] = [];
1044 $groupTree[$groupId]['id'] = $groupId;
1046 foreach ($tableData['civicrm_custom_group'] as $v) {
1047 $fullField = "civicrm_custom_group_" . $v;
1049 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1053 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1056 $groupTree[$groupId]['fields'] = [];
1059 // add the fields now (note - the query row will always contain a field)
1060 $groupTree[$groupId]['fields'][$fieldId] = [];
1061 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1063 foreach ($tableData['civicrm_custom_field'] as $v) {
1064 $fullField = "civicrm_custom_field_" . $v;
1065 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1068 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1076 * @param $entityType
1078 * @param string $cidToken
1082 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1084 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1086 // get 'Tab' and 'Tab with table' groups
1087 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1088 $customGroupDAO->whereAdd("is_active = 1");
1090 // add whereAdd for entity type
1091 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1095 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1096 $customGroupDAO->whereAdd($permissionClause);
1099 $customGroupDAO->orderBy('weight');
1100 $customGroupDAO->find();
1102 // process each group with menu tab
1103 while ($customGroupDAO->fetch()) {
1105 $group['id'] = $customGroupDAO->id
;
1106 $group['path'] = $path;
1107 $group['title'] = "$customGroupDAO->title";
1108 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1109 $group['extra'] = ['gid' => $customGroupDAO->id
];
1110 $group['table_name'] = $customGroupDAO->table_name
;
1111 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1119 * Get the table name for the entity type
1120 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1121 * tableName is 'civicrm_contact'
1123 * @param string $entityType
1124 * What entity are we extending here ?.
1129 * @see _apachesolr_civiAttachments_dereference_file_parent
1131 public static function getTableNameByEntityName($entityType) {
1133 switch ($entityType) {
1137 case 'Organization':
1138 $tableName = 'civicrm_contact';
1141 case 'Contribution':
1142 $tableName = 'civicrm_contribution';
1146 $tableName = 'civicrm_group';
1149 // DRAFTING: Verify if we cannot make it pluggable
1152 $tableName = 'civicrm_activity';
1155 case 'Relationship':
1156 $tableName = 'civicrm_relationship';
1160 $tableName = 'civicrm_membership';
1164 $tableName = 'civicrm_participant';
1168 $tableName = 'civicrm_event';
1172 $tableName = 'civicrm_grant';
1175 // need to add cases for Location, Address
1182 * Get a list of custom groups which extend a given entity type.
1183 * If there are custom-groups which only apply to certain subtypes,
1184 * those WILL be included.
1186 * @param string $entityType
1188 * @return CRM_Core_DAO_CustomGroup
1190 public static function getAllCustomGroupsByBaseEntity($entityType) {
1191 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1192 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1193 return $customGroupDAO;
1197 * Add the whereAdd clause for the DAO depending on the type of entity
1198 * the custom group is extending.
1200 * @param object $customGroupDAO
1201 * @param string $entityType
1202 * What entity are we extending here ?.
1204 * @param int $entityID
1205 * @param bool $allSubtypes
1207 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1208 $addSubtypeClause = FALSE;
1209 // This function isn't really accessible with user data but since the string
1210 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1212 $entityType = CRM_Core_DAO
::escapeString($entityType);
1214 switch ($entityType) {
1216 // if contact, get all related to contact
1217 $extendList = "'Contact','Individual','Household','Organization'";
1218 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1219 if (!$allSubtypes) {
1220 $addSubtypeClause = TRUE;
1226 case 'Organization':
1227 // is I/H/O then get I/H/O and contact
1228 $extendList = "'Contact','$entityType'";
1229 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1230 if (!$allSubtypes) {
1231 $addSubtypeClause = TRUE;
1236 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1240 if ($addSubtypeClause) {
1241 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1243 if (!empty($csType)) {
1244 $subtypeClause = [];
1245 foreach ($csType as $subtype) {
1246 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1247 CRM_Core_DAO
::VALUE_SEPARATOR
;
1248 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1250 $subtypeClause[] = "extends_entity_column_value IS NULL";
1251 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1255 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1261 * Delete the Custom Group.
1263 * @param CRM_Core_BAO_CustomGroup $group
1264 * Custom group object.
1265 * @param bool $force
1266 * whether to force the deletion, even if there are custom fields.
1269 * False if field exists for this group, true if group gets deleted.
1271 public static function deleteGroup($group, $force = FALSE) {
1273 //check whether this contain any custom fields
1274 $customField = new CRM_Core_DAO_CustomField();
1275 $customField->custom_group_id
= $group->id
;
1276 $customField->find();
1278 // return early if there are custom fields and we're not
1279 // forcing the delete, otherwise delete the fields one by one
1280 while ($customField->fetch()) {
1284 CRM_Core_BAO_CustomField
::deleteField($customField);
1287 // drop the table associated with this custom group
1288 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1290 //delete custom group
1293 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1301 * @param array $groupTree
1302 * @param array $defaults
1303 * @param bool $viewMode
1304 * @param bool $inactiveNeeded
1305 * @param int $action
1307 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1308 foreach ($groupTree as $id => $group) {
1309 if (!isset($group['fields'])) {
1312 foreach ($group['fields'] as $field) {
1313 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1314 $value = $field['element_value'];
1316 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1317 ($action != CRM_Core_Action
::UPDATE ||
1319 !array_key_exists('element_value', $field)
1322 $value = $viewMode ?
NULL : $field['default_value'];
1328 if (empty($field['element_name'])) {
1332 $elementName = $field['element_name'];
1334 switch ($field['html_type']) {
1335 case 'Multi-Select':
1337 $defaults[$elementName] = [];
1338 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1340 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1341 if (isset($value)) {
1342 foreach ($customOption as $customValue => $customLabel) {
1343 if (in_array($customValue, $checkedData)) {
1344 if ($field['html_type'] == 'CheckBox') {
1345 $defaults[$elementName][$customValue] = 1;
1348 $defaults[$elementName][$customValue] = $customValue;
1352 $defaults[$elementName][$customValue] = 0;
1358 if (isset($field['customValue']['data'])) {
1359 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1360 foreach ($customOption as $val) {
1361 if (in_array($val['value'], $checkedData)) {
1362 if ($field['html_type'] == 'CheckBox') {
1363 $defaults[$elementName][$val['value']] = 1;
1366 $defaults[$elementName][$val['value']] = $val['value'];
1370 $defaults[$elementName][$val['value']] = 0;
1375 if (is_array($value) && count($value)) {
1376 CRM_Utils_Array
::formatArrayKeys($value);
1377 $checkedValue = $value;
1380 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1382 foreach ($customOption as $val) {
1383 if (in_array($val['value'], $checkedValue)) {
1384 if ($field['html_type'] == 'CheckBox') {
1385 $defaults[$elementName][$val['value']] = 1;
1388 $defaults[$elementName][$val['value']] = $val['value'];
1396 case 'Multi-Select Country':
1397 case 'Multi-Select State/Province':
1398 if (isset($value)) {
1399 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1400 foreach ($checkedValue as $val) {
1402 $defaults[$elementName][$val] = $val;
1408 case 'Select Country':
1410 $defaults[$elementName] = $value;
1413 $config = CRM_Core_Config
::singleton();
1414 $defaults[$elementName] = $config->defaultContactCountry
;
1419 if ($field['data_type'] == "Float") {
1420 $defaults[$elementName] = (float) $value;
1422 elseif ($field['data_type'] == 'Money' &&
1423 $field['html_type'] == 'Text'
1425 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1428 $defaults[$elementName] = $value;
1436 * PostProcess function.
1438 * @param array $groupTree
1439 * @param array $params
1440 * @param bool $skipFile
1442 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1443 // Get the Custom form values and groupTree
1444 // first reset all checkbox and radio data
1445 foreach ($groupTree as $groupID => $group) {
1446 if ($groupID === 'info') {
1449 foreach ($group['fields'] as $field) {
1450 $fieldId = $field['id'];
1452 //added Multi-Select option in the below if-statement
1453 if ($field['html_type'] == 'CheckBox' ||
1454 $field['html_type'] == 'Radio' ||
1455 $field['html_type'] == 'Multi-Select'
1457 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1461 foreach ($params as $key => $val) {
1462 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1463 $match[1] == $field['id']
1469 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1470 // field exists in db so populate value from "form".
1471 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
1474 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1476 // added for CheckBox
1479 $customValue = array_keys($v);
1480 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1481 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1482 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1485 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1489 case 'Multi-Select':
1491 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1492 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1493 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1496 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1501 $date = CRM_Utils_Date
::processDate($v);
1502 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1510 // store the file in d/b
1511 $entityId = explode('=', $groupTree['info']['where'][0]);
1512 $fileParams = ['upload_date' => date('YmdHis')];
1514 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1515 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1518 $fileParams['uri'] = $v['name'];
1519 $fileParams['mime_type'] = $v['type'];
1520 CRM_Core_BAO_File
::filePostProcess($v['name'],
1521 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1522 $groupTree[$groupID]['table_name'],
1527 'custom_' . $fieldId,
1533 'entity_table' => $groupTree[$groupID]['table_name'],
1534 'entity_id' => $entityId[1],
1537 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1542 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1546 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1554 * Generic function to build all the form elements for a specific group tree.
1556 * @param CRM_Core_Form $form
1558 * @param array $groupTree
1559 * The group tree object.
1560 * @param bool $inactiveNeeded
1561 * Return inactive custom groups.
1562 * @param string $prefix
1563 * Prefix for custom grouptree assigned to template.
1565 * @throws \CiviCRM_API3_Exception
1567 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1568 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1570 foreach ($groupTree as $id => $group) {
1571 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1572 foreach ($group['fields'] as $field) {
1573 $required = CRM_Utils_Array
::value('is_required', $field);
1575 if ($field['data_type'] == 'File') {
1576 if (!empty($field['element_value']['data'])) {
1581 $fieldId = $field['id'];
1582 $elementName = $field['element_name'];
1583 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1584 if ($form->getAction() == CRM_Core_Action
::VIEW
) {
1585 $form->getElement($elementName)->freeze();
1592 * Extract the get params from the url, validate and store it in session.
1594 * @param CRM_Core_Form $form
1596 * @param string $type
1597 * The type of custom group we are using.
1600 * @throws \CRM_Core_Exception
1601 * @throws \CiviCRM_API3_Exception
1603 public static function extractGetParams(&$form, $type) {
1608 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1617 foreach ($groupTree as $group) {
1618 if (!isset($group['fields'])) {
1621 foreach ($group['fields'] as $key => $field) {
1622 $fieldName = 'custom_' . $key;
1623 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1627 if (!in_array($field['html_type'], $htmlType) ||
1628 $field['data_type'] == 'Boolean'
1630 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1632 if ($field['html_type'] == 'CheckBox' ||
1633 $field['html_type'] == 'Multi-Select'
1635 $value = str_replace("|", ",", $value);
1636 $mulValues = explode(',', $value);
1637 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1639 foreach ($mulValues as $v1) {
1640 foreach ($customOption as $coID => $coValue) {
1641 if (strtolower(trim($coValue['label'])) ==
1642 strtolower(trim($v1))
1644 $val[$coValue['value']] = 1;
1656 elseif ($field['html_type'] == 'Select' ||
1657 ($field['html_type'] == 'Radio' &&
1658 $field['data_type'] != 'Boolean'
1661 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1662 foreach ($customOption as $customID => $coValue) {
1663 if (strtolower(trim($coValue['label'])) ==
1664 strtolower(trim($value))
1666 $value = $coValue['value'];
1671 elseif ($field['data_type'] == 'Date') {
1672 $valid = CRM_Utils_Rule
::date($value);
1676 $customValue[$fieldName] = $value;
1682 return $customValue;
1686 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1687 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1689 * @param int $customFieldId
1691 * @param array $removeCustomFieldTypes
1692 * Remove custom fields of a type eg: array("Individual") ;.
1695 * false if it matches else true
1697 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1698 $query = "SELECT cg.extends as extends
1699 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1700 WHERE cg.id = cf.custom_group_id
1702 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1704 $extends = CRM_Core_DAO
::singleValueQuery($query);
1706 if (in_array($extends, $removeCustomFieldTypes)) {
1718 public static function mapTableName($table) {
1723 case 'Organization':
1724 return 'civicrm_contact';
1727 return 'civicrm_activity';
1730 return 'civicrm_group';
1732 case 'Contribution':
1733 return 'civicrm_contribution';
1735 case 'ContributionRecur':
1736 return 'civicrm_contribution_recur';
1738 case 'Relationship':
1739 return 'civicrm_relationship';
1742 return 'civicrm_event';
1745 return 'civicrm_membership';
1748 case 'ParticipantRole':
1749 case 'ParticipantEventName':
1750 case 'ParticipantEventType':
1751 return 'civicrm_participant';
1754 return 'civicrm_grant';
1757 return 'civicrm_pledge';
1760 return 'civicrm_address';
1763 return 'civicrm_campaign';
1767 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1768 $qParams = [1 => [$table, 'String']];
1769 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1772 return 'civicrm_contact';
1775 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1776 if (array_key_exists($table, $extendObjs)) {
1777 return $extendObjs[$table];
1779 CRM_Core_Error
::fatal();
1787 * @throws \Exception
1789 public static function createTable($group) {
1791 'name' => $group->table_name
,
1792 'is_multiple' => $group->is_multiple ?
1 : 0,
1793 'extends_name' => self
::mapTableName($group->extends),
1796 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1798 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1802 * Function returns formatted groupTree, so that form can be easily built in template
1804 * @param array $groupTree
1805 * @param int $groupCount
1806 * Group count by default 1, but can vary for multiple value custom data.
1807 * @param \CRM_Core_Form $form
1810 * @throws \CRM_Core_Exception
1812 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1813 $formattedGroupTree = [];
1814 $uploadNames = $formValues = [];
1816 // retrieve qf key from url
1817 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1819 // fetch submitted custom field values later use to set as a default values
1821 $submittedValues = Civi
::cache('customData')->get($qfKey);
1824 foreach ($groupTree as $key => $value) {
1825 if ($key === 'info') {
1829 // add group information
1830 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1831 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1832 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1833 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1834 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1835 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1836 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1838 // this params needed of bulding multiple values
1839 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1840 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1841 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1842 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1843 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1844 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1846 // add field information
1847 foreach ($value['fields'] as $k => $properties) {
1848 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1849 if (isset($properties['customValue']) &&
1850 !CRM_Utils_System
::isNull($properties['customValue']) &&
1851 !isset($properties['element_value'])
1853 if (isset($properties['customValue'][$groupCount])) {
1854 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1855 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1856 if ($properties['data_type'] == 'File') {
1857 $properties['element_value'] = $properties['customValue'][$groupCount];
1858 $uploadNames[] = $properties['element_name'];
1861 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1865 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1866 $formValues[$properties['element_name']] = $value;
1868 elseif (isset($submittedValues[$properties['element_name']])) {
1869 $properties['element_value'] = $submittedValues[$properties['element_name']];
1871 unset($properties['customValue']);
1872 $formattedGroupTree[$key]['fields'][$k] = $properties;
1877 if (count($formValues)) {
1878 $qf = $form->get('qfKey');
1879 $form->assign('qfKey', $qf);
1880 Civi
::cache('customData')->set($qf, $formValues);
1883 // hack for field type File
1884 $formUploadNames = $form->get('uploadNames');
1885 if (is_array($formUploadNames)) {
1886 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1889 $form->set('uploadNames', $uploadNames);
1892 return $formattedGroupTree;
1896 * Build custom data view.
1898 * @param CRM_Core_Form|CRM_Core_Page $form
1900 * @param array $groupTree
1901 * @param bool $returnCount
1902 * True if customValue count needs to be returned.
1904 * @param null $prefix
1905 * @param int $customValueId
1906 * @param int $entityId
1909 * @throws \Exception
1911 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1913 foreach ($groupTree as $key => $group) {
1914 if ($key === 'info') {
1918 foreach ($group['fields'] as $k => $properties) {
1919 $groupID = $group['id'];
1920 if (!empty($properties['customValue'])) {
1921 foreach ($properties['customValue'] as $values) {
1922 if (!empty($customValueId) && $customValueId != $values['id']) {
1925 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1926 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1927 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1928 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1929 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1930 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1931 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1932 $details[$groupID][$values['id']]['fields'][$k] = [
1933 'field_title' => CRM_Utils_Array
::value('label', $properties),
1934 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1935 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1936 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1937 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1939 // editable = whether this set contains any non-read-only fields
1940 if (!isset($details[$groupID][$values['id']]['editable'])) {
1941 $details[$groupID][$values['id']]['editable'] = FALSE;
1943 if (empty($properties['is_view'])) {
1944 $details[$groupID][$values['id']]['editable'] = TRUE;
1946 // also return contact reference contact id if user has view all or edit all contacts perm
1947 if ((CRM_Core_Permission
::check('view all contacts') ||
1948 CRM_Core_Permission
::check('edit all contacts'))
1950 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1953 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1958 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1959 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1960 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1961 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1962 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1963 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1964 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
1965 $details[$groupID][0]['fields'][$k] = ['field_title' => CRM_Utils_Array
::value('label', $properties)];
1971 // return a single value count if group id is passed to function
1972 // else return a groupId and count mapped array
1974 return count($details[$gID]);
1978 foreach ($details as $key => $value) {
1979 $countValue[$key] = count($details[$key]);
1985 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1991 * Get the custom group titles by custom field ids.
1993 * @param array $fieldIds
1994 * Array of custom field ids.
1996 * @return array|NULL
1997 * array consisting of groups and fields labels with ids.
1999 public static function getGroupTitles($fieldIds) {
2000 if (!is_array($fieldIds) && empty($fieldIds)) {
2005 $fIds = "(" . implode(',', $fieldIds) . ")";
2008 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2009 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2010 FROM civicrm_custom_group, civicrm_custom_field
2011 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2012 AND civicrm_custom_field.id IN {$fIds}";
2014 $dao = CRM_Core_DAO
::executeQuery($query);
2015 while ($dao->fetch()) {
2016 $groupLabels[$dao->fieldID
] = [
2017 'fieldID' => $dao->fieldID
,
2018 'fieldLabel' => $dao->fieldLabel
,
2019 'groupID' => $dao->groupID
,
2020 'groupTitle' => $dao->groupTitle
,
2024 return $groupLabels;
2027 public static function dropAllTables() {
2028 $query = "SELECT table_name FROM civicrm_custom_group";
2029 $dao = CRM_Core_DAO
::executeQuery($query);
2031 while ($dao->fetch()) {
2032 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2033 CRM_Core_DAO
::executeQuery($query);
2038 * Check whether custom group is empty or not.
2044 * true if empty otherwise false.
2046 public static function isGroupEmpty($gID) {
2051 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2056 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2057 $value = CRM_Core_DAO
::singleValueQuery($query);
2059 if (empty($value)) {
2067 * Get the list of types for objects that a custom group extends to.
2069 * @param array $types
2070 * Var which should have the list appended.
2074 * @throws \Exception
2076 public static function getExtendedObjectTypes(&$types = []) {
2077 static $flag = FALSE, $objTypes = [];
2081 CRM_Core_OptionValue
::getValues(['name' => 'cg_extend_objects'], $extendObjs);
2083 foreach ($extendObjs as $ovId => $ovValues) {
2084 if ($ovValues['description']) {
2085 // description is expected to be a callback func to subtypes
2086 list($callback, $args) = explode(';', trim($ovValues['description']));
2092 if (!is_array($args)) {
2093 CRM_Core_Error
::fatal('Arg is not of type array');
2096 list($className) = explode('::', $callback);
2097 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
2099 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2105 $types = array_merge($types, $objTypes);
2110 * @param int $customGroupId
2111 * @param int $entityId
2115 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2116 // check whether the group is multiple
2117 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2118 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2119 $hasReachedMax = FALSE;
2121 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2123 if (!$maxMultiple) {
2124 $hasReachedMax = FALSE;
2127 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2128 // count the number of entries for a entity
2129 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2130 $params = [1 => [$entityId, 'Integer']];
2131 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2133 if ($count >= $maxMultiple) {
2134 $hasReachedMax = TRUE;
2138 return $hasReachedMax;
2144 public static function getMultipleFieldGroup() {
2145 $multipleGroup = [];
2146 $dao = new CRM_Core_DAO_CustomGroup();
2147 $dao->is_multiple
= 1;
2148 $dao->is_active
= 1;
2150 while ($dao->fetch()) {
2151 $multipleGroup[$dao->id
] = $dao->title
;
2153 return $multipleGroup;
2157 * Build the metadata tree for the custom group.
2159 * @param string $entityType
2160 * @param array $toReturn
2161 * @param array $subTypes
2162 * @param string $queryString
2163 * @param array $params
2164 * @param string $subType
2167 * @throws \CRM_Core_Exception
2169 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2170 $groupTree = $multipleFieldGroups = [];
2171 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
2172 $customValueTables = [];
2175 while ($crmDAO->fetch()) {
2177 $groupID = $crmDAO->civicrm_custom_group_id
;
2178 $fieldId = $crmDAO->civicrm_custom_field_id
;
2179 if ($crmDAO->civicrm_custom_group_is_multiple
) {
2180 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
2182 // create an array for groups if it does not exist
2183 if (!array_key_exists($groupID, $groupTree)) {
2184 $groupTree[$groupID] = [];
2185 $groupTree[$groupID]['id'] = $groupID;
2187 // populate the group information
2188 foreach ($toReturn['custom_group'] as $fieldName) {
2189 $fullFieldName = "civicrm_custom_group_$fieldName";
2190 if ($fieldName == 'id' ||
2191 is_null($crmDAO->$fullFieldName)
2196 // This is an old bit of code - per the CRM number & probably does not work reliably if
2197 // that one contact sub-type exists.
2198 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2199 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
2201 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2203 $groupTree[$groupID]['fields'] = [];
2205 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = [];
2208 // add the fields now (note - the query row will always contain a field)
2209 // we only reset this once, since multiple values come is as multiple rows
2210 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2211 $groupTree[$groupID]['fields'][$fieldId] = [];
2214 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
2215 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2216 // populate information for a custom field
2217 foreach ($toReturn['custom_field'] as $fieldName) {
2218 $fullFieldName = "civicrm_custom_field_$fieldName";
2219 if ($fieldName == 'id' ||
2220 is_null($crmDAO->$fullFieldName)
2224 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2228 if (!empty($customValueTables)) {
2229 $groupTree['info'] = ['tables' => $customValueTables];
2231 return [$multipleFieldGroups, $groupTree];