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)) {
306 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
309 'extends' => 'Activity',
310 'extends_entity_column_id' => NULL,
311 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded([$activityTypeId]),
312 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
316 $result = civicrm_api('CustomGroup', 'create', $params);
317 return !$result['is_error'];
321 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
322 * This may also include entity specific data values.
324 * An array containing all custom groups and their custom fields is returned.
326 * @param string $entityType
327 * Of the contact whose contact type is needed.
328 * @param array $toReturn
329 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
330 * @param int $entityID
331 * @param int $groupID
332 * @param array $subTypes
333 * @param string $subName
334 * @param bool $fromCache
335 * @param bool $onlySubType
336 * Only return specified subtype or return specified subtype + unrestricted fields.
337 * @param bool $returnAll
338 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
339 * api - through which it is properly tested - so can be refactored with some comfort.)
341 * @param bool $checkPermission
342 * @param string|int $singleRecord
343 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
344 * @param bool $showPublicOnly
347 * Custom field 'tree'.
349 * The returned array is keyed by group id and has the custom group table fields
350 * and a subkey 'fields' holding the specific custom fields.
351 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
352 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
354 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
355 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
356 * With caching the performance impact would be small & the function would be cleaner
358 * @throws \CRM_Core_Exception
360 public static function getTree(
370 $checkPermission = TRUE,
371 $singleRecord = NULL,
372 $showPublicOnly = FALSE
375 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
377 if (!is_array($subTypes)) {
378 if (empty($subTypes)) {
382 if (stristr($subTypes, ',')) {
383 $subTypes = explode(',', $subTypes);
386 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
393 // legacy hardcoded list of data to return
427 'extends_entity_column_id',
428 'extends_entity_column_value',
432 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
433 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
434 if ($is_public_version) {
435 $tableData['custom_group'][] = 'is_public';
437 if (!$toReturn ||
!is_array($toReturn)) {
438 $toReturn = $tableData;
441 // Supply defaults and remove unknown array keys
442 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
443 // Merge in required fields that we must have
444 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
445 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
446 // Validate return fields
447 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
448 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
453 foreach ($toReturn as $tableName => $tableColumn) {
454 foreach ($tableColumn as $columnName) {
455 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
458 $strSelect = "SELECT " . implode(', ', $select);
460 // from, where, order by
462 FROM civicrm_custom_group
463 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
466 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
467 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
468 $entityType == 'Household'
470 $in = "'$entityType', 'Contact'";
472 elseif (strpos($entityType, "'") !== FALSE) {
473 // this allows the calling function to send in multiple entity types
478 $in = "'$entityType'";
483 if (!empty($subTypes)) {
484 foreach ($subTypes as $key => $subType) {
485 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
487 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
489 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
493 WHERE civicrm_custom_group.is_active = 1
494 AND civicrm_custom_field.is_active = 1
495 AND civicrm_custom_group.extends IN ($in)
499 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
500 $params[$sqlParamKey] = [$subName, 'String'];
501 $sqlParamKey = $sqlParamKey +
1;
506 WHERE civicrm_custom_group.is_active = 1
507 AND civicrm_custom_field.is_active = 1
508 AND civicrm_custom_group.extends IN ($in)
511 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
516 // since we want a specific group id we add it to the where clause
517 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
518 $params[$sqlParamKey] = [$groupID, 'Integer'];
521 // since groupID is false we need to show all Inline groups
522 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
524 if ($checkPermission) {
525 // ensure that the user has access to these custom groups
526 $strWhere .= " AND " .
527 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
528 'civicrm_custom_group.'
532 if ($showPublicOnly && $is_public_version) {
533 $strWhere .= "AND civicrm_custom_group.is_public = 1";
537 ORDER BY civicrm_custom_group.weight,
538 civicrm_custom_group.title,
539 civicrm_custom_field.weight,
540 civicrm_custom_field.label
543 // final query string
544 $queryString = "$strSelect $strFrom $strWhere $orderBy";
546 // lets see if we can retrieve the groupTree from cache
547 $cacheString = $queryString;
549 $cacheString .= "_{$groupID}";
552 $cacheString .= "_Inline";
555 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
556 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
557 $cache = CRM_Utils_Cache
::singleton();
559 $groupTree = $cache->get($cacheKey);
560 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
563 if (empty($groupTree)) {
564 $groupTree = $multipleFieldGroups = [];
565 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
566 $customValueTables = [];
569 while ($crmDAO->fetch()) {
571 $groupID = $crmDAO->civicrm_custom_group_id
;
572 $fieldId = $crmDAO->civicrm_custom_field_id
;
573 if ($crmDAO->civicrm_custom_group_is_multiple
) {
574 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
576 // create an array for groups if it does not exist
577 if (!array_key_exists($groupID, $groupTree)) {
578 $groupTree[$groupID] = [];
579 $groupTree[$groupID]['id'] = $groupID;
581 // populate the group information
582 foreach ($toReturn['custom_group'] as $fieldName) {
583 $fullFieldName = "civicrm_custom_group_$fieldName";
584 if ($fieldName == 'id' ||
585 is_null($crmDAO->$fullFieldName)
590 // This is an old bit of code - per the CRM number & probably does not work reliably if
591 // that one contact sub-type exists.
592 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
593 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
595 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
597 $groupTree[$groupID]['fields'] = [];
599 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = [];
602 // add the fields now (note - the query row will always contain a field)
603 // we only reset this once, since multiple values come is as multiple rows
604 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
605 $groupTree[$groupID]['fields'][$fieldId] = [];
608 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
609 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
610 // populate information for a custom field
611 foreach ($toReturn['custom_field'] as $fieldName) {
612 $fullFieldName = "civicrm_custom_field_$fieldName";
613 if ($fieldName == 'id' ||
614 is_null($crmDAO->$fullFieldName)
618 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
622 if (!empty($customValueTables)) {
623 $groupTree['info'] = ['tables' => $customValueTables];
626 $cache->set($cacheKey, $groupTree);
627 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
629 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
630 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
631 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
632 $singleFieldTables = [];
633 // now that we have all the groups and fields, lets get the values
634 // since we need to know the table and field names
635 // add info to groupTree
637 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
638 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
640 $select = $from = $where = [];
641 $groupTree['info']['where'] = NULL;
643 foreach ($groupTree['info']['tables'] as $table => $fields) {
644 $groupTree['info']['from'][] = $table;
646 "{$table}.id as {$table}_id",
647 "{$table}.entity_id as {$table}_entity_id",
649 foreach ($fields as $column => $dontCare) {
650 $select[] = "{$table}.{$column} as {$table}_{$column}";
652 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
654 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
655 if (in_array($table, $multipleFieldGroups) &&
656 self
::customGroupDataExistsForEntity($entityID, $table)
658 $entityMultipleSelectClauses[$table] = $select;
661 $singleFieldTables[] = $table;
662 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
667 if ($entityID && !empty($singleFieldTables)) {
668 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
670 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
671 if (!empty($multipleFieldTablesWithEntityData)) {
672 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
680 * Clean and validate the filter before it is used in a db query.
682 * @param string $entityType
683 * @param string $subType
686 * @throws \CRM_Core_Exception
688 protected static function validateSubTypeByEntity($entityType, $subType) {
689 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
690 if (is_numeric($subType)) {
694 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
695 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
697 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
698 throw new CRM_Core_Exception('Invalid Entity Filter');
700 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
701 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
702 if (!array_key_exists($subType, $subTypes)) {
703 throw new CRM_Core_Exception('Invalid Filter');
709 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
710 * a WHERE condition for rows that include $value. Use whereListHas().
712 * @param string $column
713 * @param string $value
714 * @param string $delimiter
718 static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
719 $bareValue = trim($value, $delimiter); // ?
720 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
721 return "($column LIKE \"$escapedValue\")";
725 * Check whether the custom group has any data for the given entity.
727 * @param int $entityID
728 * Id of entity for whom we are checking data for.
729 * @param string $table
730 * Table that we are checking.
732 * @param bool $getCount
735 * does this entity have data in this custom table
737 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
741 WHERE entity_id = $entityID
743 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
745 return $recordExists;
747 return $recordExists ?
TRUE : FALSE;
751 * Build the group tree for Custom fields which are not 'is_multiple'
753 * The combination of all these fields in one query with a 'using' join was not working for
754 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
755 * mechanism as it seemed to be acceptable in this context
757 * @param array $groupTree
758 * (reference) group tree array which is being built.
759 * @param int $entityID
760 * Id of entity for whom the tree is being build up.
761 * @param array $entitySingleSelectClauses
762 * Array of select clauses relevant to the entity.
763 * @param array $singleFieldTablesWithEntityData
764 * Array of tables in which this entity has data.
766 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
767 $select = implode(', ', $entitySingleSelectClauses);
768 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
769 foreach ($singleFieldTablesWithEntityData as $table) {
770 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
776 WHERE first.entity_id = $entityID
778 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
782 * Build the group tree for Custom fields which are 'is_multiple'
784 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
786 * @param array $groupTree
787 * (reference) group tree array which is being built.
788 * @param int $entityID
789 * Id of entity for whom the tree is being build up.
790 * @param array $entityMultipleSelectClauses
791 * Array of select clauses relevant to the entity.
792 * @param array $multipleFieldTablesWithEntityData
793 * Array of tables in which this entity has data.
794 * @param string|int $singleRecord
795 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
797 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
798 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
799 $select = implode(',', $selectClauses);
803 WHERE entity_id = $entityID
806 $offset = $singleRecord - 1;
807 $query .= " LIMIT {$offset}, 1";
809 self
::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
814 * Build the tree entity data - starting from a query retrieving the custom fields build the group
815 * tree data for the relevant entity (entity is included in the query).
817 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
819 * @param array $groupTree
820 * (reference) group tree array which is being built.
821 * @param string $query
822 * @param array $includedTables
823 * Tables to include - required because the function (for historical reasons).
824 * iterates through the group tree
825 * @param string|int $singleRecord
826 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
828 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
829 $dao = CRM_Core_DAO
::executeQuery($query);
830 while ($dao->fetch()) {
831 foreach ($groupTree as $groupID => $group) {
832 if ($groupID === 'info') {
835 $table = $groupTree[$groupID]['table_name'];
836 //working from the groupTree instead of the table list means we have to iterate & exclude.
837 // this could possibly be re-written as other parts of the function have been refactored
838 // for now we just check if the given table is to be included in this function
839 if (!in_array($table, $includedTables)) {
842 foreach ($group['fields'] as $fieldID => $dontCare) {
843 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
850 * Build the entity-specific custom data into the group tree on a per-field basis
853 * Object representing the custom field to be populated into the groupTree.
854 * @param array $groupTree
855 * (reference) the group tree being build.
856 * @param string $table
858 * @param int $groupID
860 * @param int $fieldID
862 * @param string|int $singleRecord
863 * holds 'new' or id if loading view/edit/copy for a single record.
865 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
866 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
867 $idName = "{$table}_id";
868 $fieldName = "{$table}_{$column}";
869 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
870 if ($dataType == 'File') {
871 if (isset($dao->$fieldName)) {
872 $config = CRM_Core_Config
::singleton();
873 $fileDAO = new CRM_Core_DAO_File();
874 $fileDAO->id
= $dao->$fieldName;
876 if ($fileDAO->find(TRUE)) {
877 $entityIDName = "{$table}_entity_id";
878 $fileHash = CRM_Core_BAO_File
::generateFileHash($dao->$entityIDName, $fileDAO->id
);
879 $customValue['id'] = $dao->$idName;
880 $customValue['data'] = $fileDAO->uri
;
881 $customValue['fid'] = $fileDAO->id
;
882 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
883 $customValue['displayURL'] = NULL;
884 $deleteExtra = ts('Are you sure you want to delete attached file.');
886 CRM_Core_Action
::DELETE
=> [
887 'name' => ts('Delete Attached File'),
888 'url' => 'civicrm/file',
889 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
890 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
891 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
894 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
895 CRM_Core_Action
::DELETE
,
897 'id' => $fileDAO->id
,
898 'eid' => $dao->$entityIDName,
904 'file.manage.delete',
908 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
909 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
910 if ($fileDAO->mime_type
== "image/jpeg" ||
911 $fileDAO->mime_type
== "image/pjpeg" ||
912 $fileDAO->mime_type
== "image/gif" ||
913 $fileDAO->mime_type
== "image/x-png" ||
914 $fileDAO->mime_type
== "image/png"
916 $customValue['displayURL'] = $customValue['fileURL'];
917 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
922 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
924 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId);
925 if ($path && file_exists($path)) {
926 list($imageWidth, $imageHeight) = getimagesize($path);
927 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
928 $customValue['imageThumbWidth'] = $imageThumbWidth;
929 $customValue['imageThumbHeight'] = $imageThumbHeight;
936 'id' => $dao->$idName,
943 'id' => $dao->$idName,
944 'data' => $dao->$fieldName,
948 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
949 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
951 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
952 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
954 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
955 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
958 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
963 * Get the group title.
971 public static function getTitle($id) {
972 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
976 * Get custom group details for a group.
978 * An array containing custom group details (including their custom field) is returned.
980 * @param int $groupId
981 * Group id whose details are needed.
982 * @param bool $searchable
983 * Is this field searchable.
984 * @param array $extends
985 * Which table does it extend if any.
987 * @param bool $inSelector
990 * array consisting of all group and field details
992 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
996 // using tableData to build the queryString
998 'civicrm_custom_field' => [
1022 'civicrm_custom_group' => [
1029 'collapse_adv_display',
1031 'extends_entity_column_value',
1039 foreach ($tableData as $tableName => $tableColumn) {
1040 foreach ($tableColumn as $columnName) {
1041 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
1044 $select = 'SELECT ' . implode(', ', $s);
1046 // from, where, order by
1047 $from = " FROM civicrm_custom_field, civicrm_custom_group";
1048 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
1049 AND civicrm_custom_group.is_active = 1
1050 AND civicrm_custom_field.is_active = 1 ";
1052 $params[1] = [$groupId, 'Integer'];
1053 $where .= " AND civicrm_custom_group.id = %1";
1057 $where .= " AND civicrm_custom_field.is_searchable = 1";
1061 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1066 foreach ($extends as $e) {
1067 $clause[] = "civicrm_custom_group.extends = '$e'";
1069 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1071 //include case activities customdata if case is enabled
1072 if (in_array('Activity', $extends)) {
1073 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1074 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1075 $params[2] = [CRM_Core_DAO
::VALUE_SEPARATOR
, 'String'];
1079 // ensure that the user has access to these custom groups
1081 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1082 'civicrm_custom_group.'
1085 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1087 // final query string
1088 $queryString = $select . $from . $where . $orderBy;
1091 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1094 while ($crmDAO->fetch()) {
1095 $groupId = $crmDAO->civicrm_custom_group_id
;
1096 $fieldId = $crmDAO->civicrm_custom_field_id
;
1098 // create an array for groups if it does not exist
1099 if (!array_key_exists($groupId, $groupTree)) {
1100 $groupTree[$groupId] = [];
1101 $groupTree[$groupId]['id'] = $groupId;
1103 foreach ($tableData['civicrm_custom_group'] as $v) {
1104 $fullField = "civicrm_custom_group_" . $v;
1106 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1110 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1113 $groupTree[$groupId]['fields'] = [];
1116 // add the fields now (note - the query row will always contain a field)
1117 $groupTree[$groupId]['fields'][$fieldId] = [];
1118 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1120 foreach ($tableData['civicrm_custom_field'] as $v) {
1121 $fullField = "civicrm_custom_field_" . $v;
1122 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1125 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1133 * @param $entityType
1135 * @param string $cidToken
1139 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1141 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1143 // get 'Tab' and 'Tab with table' groups
1144 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1145 $customGroupDAO->whereAdd("is_active = 1");
1147 // add whereAdd for entity type
1148 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1152 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1153 $customGroupDAO->whereAdd($permissionClause);
1156 $customGroupDAO->orderBy('weight');
1157 $customGroupDAO->find();
1159 // process each group with menu tab
1160 while ($customGroupDAO->fetch()) {
1162 $group['id'] = $customGroupDAO->id
;
1163 $group['path'] = $path;
1164 $group['title'] = "$customGroupDAO->title";
1165 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1166 $group['extra'] = ['gid' => $customGroupDAO->id
];
1167 $group['table_name'] = $customGroupDAO->table_name
;
1168 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1176 * Get the table name for the entity type
1177 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1178 * tableName is 'civicrm_contact'
1180 * @param string $entityType
1181 * What entity are we extending here ?.
1186 * @see _apachesolr_civiAttachments_dereference_file_parent
1188 public static function getTableNameByEntityName($entityType) {
1190 switch ($entityType) {
1194 case 'Organization':
1195 $tableName = 'civicrm_contact';
1198 case 'Contribution':
1199 $tableName = 'civicrm_contribution';
1203 $tableName = 'civicrm_group';
1206 // DRAFTING: Verify if we cannot make it pluggable
1209 $tableName = 'civicrm_activity';
1212 case 'Relationship':
1213 $tableName = 'civicrm_relationship';
1217 $tableName = 'civicrm_membership';
1221 $tableName = 'civicrm_participant';
1225 $tableName = 'civicrm_event';
1229 $tableName = 'civicrm_grant';
1232 // need to add cases for Location, Address
1239 * Get a list of custom groups which extend a given entity type.
1240 * If there are custom-groups which only apply to certain subtypes,
1241 * those WILL be included.
1243 * @param string $entityType
1245 * @return CRM_Core_DAO_CustomGroup
1247 public static function getAllCustomGroupsByBaseEntity($entityType) {
1248 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1249 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1250 return $customGroupDAO;
1254 * Add the whereAdd clause for the DAO depending on the type of entity
1255 * the custom group is extending.
1257 * @param object $customGroupDAO
1258 * @param string $entityType
1259 * What entity are we extending here ?.
1261 * @param int $entityID
1262 * @param bool $allSubtypes
1264 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1265 $addSubtypeClause = FALSE;
1266 // This function isn't really accessible with user data but since the string
1267 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1269 $entityType = CRM_Core_DAO
::escapeString($entityType);
1271 switch ($entityType) {
1273 // if contact, get all related to contact
1274 $extendList = "'Contact','Individual','Household','Organization'";
1275 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1276 if (!$allSubtypes) {
1277 $addSubtypeClause = TRUE;
1283 case 'Organization':
1284 // is I/H/O then get I/H/O and contact
1285 $extendList = "'Contact','$entityType'";
1286 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1287 if (!$allSubtypes) {
1288 $addSubtypeClause = TRUE;
1293 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1297 if ($addSubtypeClause) {
1298 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1300 if (!empty($csType)) {
1301 $subtypeClause = [];
1302 foreach ($csType as $subtype) {
1303 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1304 CRM_Core_DAO
::VALUE_SEPARATOR
;
1305 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1307 $subtypeClause[] = "extends_entity_column_value IS NULL";
1308 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1312 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1318 * Delete the Custom Group.
1320 * @param CRM_Core_BAO_CustomGroup $group
1321 * Custom group object.
1322 * @param bool $force
1323 * whether to force the deletion, even if there are custom fields.
1326 * False if field exists for this group, true if group gets deleted.
1328 public static function deleteGroup($group, $force = FALSE) {
1330 //check whether this contain any custom fields
1331 $customField = new CRM_Core_DAO_CustomField();
1332 $customField->custom_group_id
= $group->id
;
1333 $customField->find();
1335 // return early if there are custom fields and we're not
1336 // forcing the delete, otherwise delete the fields one by one
1337 while ($customField->fetch()) {
1341 CRM_Core_BAO_CustomField
::deleteField($customField);
1344 // drop the table associated with this custom group
1345 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1347 //delete custom group
1350 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1358 * @param array $groupTree
1359 * @param array $defaults
1360 * @param bool $viewMode
1361 * @param bool $inactiveNeeded
1362 * @param int $action
1364 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1365 foreach ($groupTree as $id => $group) {
1366 if (!isset($group['fields'])) {
1369 foreach ($group['fields'] as $field) {
1370 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1371 $value = $field['element_value'];
1373 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1374 ($action != CRM_Core_Action
::UPDATE ||
1376 !array_key_exists('element_value', $field)
1379 $value = $viewMode ?
NULL : $field['default_value'];
1385 if (empty($field['element_name'])) {
1389 $elementName = $field['element_name'];
1391 switch ($field['html_type']) {
1392 case 'Multi-Select':
1394 $defaults[$elementName] = [];
1395 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1397 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1398 if (isset($value)) {
1399 foreach ($customOption as $customValue => $customLabel) {
1400 if (in_array($customValue, $checkedData)) {
1401 if ($field['html_type'] == 'CheckBox') {
1402 $defaults[$elementName][$customValue] = 1;
1405 $defaults[$elementName][$customValue] = $customValue;
1409 $defaults[$elementName][$customValue] = 0;
1415 if (isset($field['customValue']['data'])) {
1416 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1417 foreach ($customOption as $val) {
1418 if (in_array($val['value'], $checkedData)) {
1419 if ($field['html_type'] == 'CheckBox') {
1420 $defaults[$elementName][$val['value']] = 1;
1423 $defaults[$elementName][$val['value']] = $val['value'];
1427 $defaults[$elementName][$val['value']] = 0;
1432 if (is_array($value) && count($value)) {
1433 CRM_Utils_Array
::formatArrayKeys($value);
1434 $checkedValue = $value;
1437 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1439 foreach ($customOption as $val) {
1440 if (in_array($val['value'], $checkedValue)) {
1441 if ($field['html_type'] == 'CheckBox') {
1442 $defaults[$elementName][$val['value']] = 1;
1445 $defaults[$elementName][$val['value']] = $val['value'];
1453 case 'Multi-Select Country':
1454 case 'Multi-Select State/Province':
1455 if (isset($value)) {
1456 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1457 foreach ($checkedValue as $val) {
1459 $defaults[$elementName][$val] = $val;
1465 case 'Select Country':
1467 $defaults[$elementName] = $value;
1470 $config = CRM_Core_Config
::singleton();
1471 $defaults[$elementName] = $config->defaultContactCountry
;
1476 if ($field['data_type'] == "Float") {
1477 $defaults[$elementName] = (float) $value;
1479 elseif ($field['data_type'] == 'Money' &&
1480 $field['html_type'] == 'Text'
1482 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1485 $defaults[$elementName] = $value;
1493 * PostProcess function.
1495 * @param array $groupTree
1496 * @param array $params
1497 * @param bool $skipFile
1499 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1500 // Get the Custom form values and groupTree
1501 // first reset all checkbox and radio data
1502 foreach ($groupTree as $groupID => $group) {
1503 if ($groupID === 'info') {
1506 foreach ($group['fields'] as $field) {
1507 $fieldId = $field['id'];
1509 //added Multi-Select option in the below if-statement
1510 if ($field['html_type'] == 'CheckBox' ||
1511 $field['html_type'] == 'Radio' ||
1512 $field['html_type'] == 'Multi-Select'
1514 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1518 foreach ($params as $key => $val) {
1519 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1520 $match[1] == $field['id']
1526 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1527 // field exists in db so populate value from "form".
1528 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
1531 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1533 // added for CheckBox
1536 $customValue = array_keys($v);
1537 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1538 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1539 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1542 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1546 case 'Multi-Select':
1548 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1549 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1550 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1553 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1558 $date = CRM_Utils_Date
::processDate($v);
1559 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1567 // store the file in d/b
1568 $entityId = explode('=', $groupTree['info']['where'][0]);
1569 $fileParams = ['upload_date' => date('YmdHis')];
1571 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1572 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1575 $fileParams['uri'] = $v['name'];
1576 $fileParams['mime_type'] = $v['type'];
1577 CRM_Core_BAO_File
::filePostProcess($v['name'],
1578 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1579 $groupTree[$groupID]['table_name'],
1584 'custom_' . $fieldId,
1590 'entity_table' => $groupTree[$groupID]['table_name'],
1591 'entity_id' => $entityId[1],
1594 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1599 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1603 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1611 * Generic function to build all the form elements for a specific group tree.
1613 * @param CRM_Core_Form $form
1615 * @param array $groupTree
1616 * The group tree object.
1617 * @param bool $inactiveNeeded
1618 * Return inactive custom groups.
1619 * @param string $prefix
1620 * Prefix for custom grouptree assigned to template.
1622 * @throws \CiviCRM_API3_Exception
1624 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1625 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1627 foreach ($groupTree as $id => $group) {
1628 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1629 foreach ($group['fields'] as $field) {
1630 $required = CRM_Utils_Array
::value('is_required', $field);
1632 if ($field['data_type'] == 'File') {
1633 if (!empty($field['element_value']['data'])) {
1638 $fieldId = $field['id'];
1639 $elementName = $field['element_name'];
1640 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1641 if ($form->getAction() == CRM_Core_Action
::VIEW
) {
1642 $form->getElement($elementName)->freeze();
1649 * Extract the get params from the url, validate and store it in session.
1651 * @param CRM_Core_Form $form
1653 * @param string $type
1654 * The type of custom group we are using.
1657 * @throws \CRM_Core_Exception
1658 * @throws \CiviCRM_API3_Exception
1660 public static function extractGetParams(&$form, $type) {
1665 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1674 foreach ($groupTree as $group) {
1675 if (!isset($group['fields'])) {
1678 foreach ($group['fields'] as $key => $field) {
1679 $fieldName = 'custom_' . $key;
1680 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1684 if (!in_array($field['html_type'], $htmlType) ||
1685 $field['data_type'] == 'Boolean'
1687 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1689 if ($field['html_type'] == 'CheckBox' ||
1690 $field['html_type'] == 'Multi-Select'
1692 $value = str_replace("|", ",", $value);
1693 $mulValues = explode(',', $value);
1694 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1696 foreach ($mulValues as $v1) {
1697 foreach ($customOption as $coID => $coValue) {
1698 if (strtolower(trim($coValue['label'])) ==
1699 strtolower(trim($v1))
1701 $val[$coValue['value']] = 1;
1713 elseif ($field['html_type'] == 'Select' ||
1714 ($field['html_type'] == 'Radio' &&
1715 $field['data_type'] != 'Boolean'
1718 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1719 foreach ($customOption as $customID => $coValue) {
1720 if (strtolower(trim($coValue['label'])) ==
1721 strtolower(trim($value))
1723 $value = $coValue['value'];
1728 elseif ($field['data_type'] == 'Date') {
1729 $valid = CRM_Utils_Rule
::date($value);
1733 $customValue[$fieldName] = $value;
1739 return $customValue;
1743 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1744 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1746 * @param int $customFieldId
1748 * @param array $removeCustomFieldTypes
1749 * Remove custom fields of a type eg: array("Individual") ;.
1752 * false if it matches else true
1754 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1755 $query = "SELECT cg.extends as extends
1756 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1757 WHERE cg.id = cf.custom_group_id
1759 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1761 $extends = CRM_Core_DAO
::singleValueQuery($query);
1763 if (in_array($extends, $removeCustomFieldTypes)) {
1775 public static function mapTableName($table) {
1780 case 'Organization':
1781 return 'civicrm_contact';
1784 return 'civicrm_activity';
1787 return 'civicrm_group';
1789 case 'Contribution':
1790 return 'civicrm_contribution';
1792 case 'ContributionRecur':
1793 return 'civicrm_contribution_recur';
1795 case 'Relationship':
1796 return 'civicrm_relationship';
1799 return 'civicrm_event';
1802 return 'civicrm_membership';
1805 case 'ParticipantRole':
1806 case 'ParticipantEventName':
1807 case 'ParticipantEventType':
1808 return 'civicrm_participant';
1811 return 'civicrm_grant';
1814 return 'civicrm_pledge';
1817 return 'civicrm_address';
1820 return 'civicrm_campaign';
1824 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1825 $qParams = [1 => [$table, 'String']];
1826 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1829 return 'civicrm_contact';
1832 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1833 if (array_key_exists($table, $extendObjs)) {
1834 return $extendObjs[$table];
1836 CRM_Core_Error
::fatal();
1844 * @throws \Exception
1846 public static function createTable($group) {
1848 'name' => $group->table_name
,
1849 'is_multiple' => $group->is_multiple ?
1 : 0,
1850 'extends_name' => self
::mapTableName($group->extends),
1853 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1855 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1859 * Function returns formatted groupTree, so that form can be easily built in template
1861 * @param array $groupTree
1862 * @param int $groupCount
1863 * Group count by default 1, but can vary for multiple value custom data.
1864 * @param \CRM_Core_Form $form
1867 * @throws \CRM_Core_Exception
1869 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1870 $formattedGroupTree = [];
1871 $uploadNames = $formValues = [];
1873 // retrieve qf key from url
1874 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1876 // fetch submitted custom field values later use to set as a default values
1878 $submittedValues = CRM_Core_BAO_Cache
::getItem('custom data', $qfKey);
1881 foreach ($groupTree as $key => $value) {
1882 if ($key === 'info') {
1886 // add group information
1887 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1888 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1889 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1890 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1891 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1892 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1893 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1895 // this params needed of bulding multiple values
1896 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1897 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1898 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1899 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1900 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1901 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1903 // add field information
1904 foreach ($value['fields'] as $k => $properties) {
1905 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1906 if (isset($properties['customValue']) &&
1907 !CRM_Utils_System
::isNull($properties['customValue']) &&
1908 !isset($properties['element_value'])
1910 if (isset($properties['customValue'][$groupCount])) {
1911 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1912 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1913 if ($properties['data_type'] == 'File') {
1914 $properties['element_value'] = $properties['customValue'][$groupCount];
1915 $uploadNames[] = $properties['element_name'];
1918 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1922 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1923 $formValues[$properties['element_name']] = $value;
1925 elseif (isset($submittedValues[$properties['element_name']])) {
1926 $properties['element_value'] = $submittedValues[$properties['element_name']];
1928 unset($properties['customValue']);
1929 $formattedGroupTree[$key]['fields'][$k] = $properties;
1934 if (count($formValues)) {
1935 $qf = $form->get('qfKey');
1936 $form->assign('qfKey', $qf);
1937 CRM_Core_BAO_Cache
::setItem($formValues, 'custom data', $qf);
1940 // hack for field type File
1941 $formUploadNames = $form->get('uploadNames');
1942 if (is_array($formUploadNames)) {
1943 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1946 $form->set('uploadNames', $uploadNames);
1949 return $formattedGroupTree;
1953 * Build custom data view.
1955 * @param CRM_Core_Form|CRM_Core_Page $form
1957 * @param array $groupTree
1958 * @param bool $returnCount
1959 * True if customValue count needs to be returned.
1961 * @param null $prefix
1962 * @param int $customValueId
1963 * @param int $entityId
1966 * @throws \Exception
1968 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1970 foreach ($groupTree as $key => $group) {
1971 if ($key === 'info') {
1975 foreach ($group['fields'] as $k => $properties) {
1976 $groupID = $group['id'];
1977 if (!empty($properties['customValue'])) {
1978 foreach ($properties['customValue'] as $values) {
1979 if (!empty($customValueId) && $customValueId != $values['id']) {
1982 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1983 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1984 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1985 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1986 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1987 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1988 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1989 $details[$groupID][$values['id']]['fields'][$k] = [
1990 'field_title' => CRM_Utils_Array
::value('label', $properties),
1991 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1992 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1993 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1994 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1996 // editable = whether this set contains any non-read-only fields
1997 if (!isset($details[$groupID][$values['id']]['editable'])) {
1998 $details[$groupID][$values['id']]['editable'] = FALSE;
2000 if (empty($properties['is_view'])) {
2001 $details[$groupID][$values['id']]['editable'] = TRUE;
2003 // also return contact reference contact id if user has view all or edit all contacts perm
2004 if ((CRM_Core_Permission
::check('view all contacts') ||
2005 CRM_Core_Permission
::check('edit all contacts'))
2007 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
2010 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
2015 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
2016 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
2017 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
2018 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
2019 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
2020 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
2021 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
2022 $details[$groupID][0]['fields'][$k] = ['field_title' => CRM_Utils_Array
::value('label', $properties)];
2028 // return a single value count if group id is passed to function
2029 // else return a groupId and count mapped array
2031 return count($details[$gID]);
2035 foreach ($details as $key => $value) {
2036 $countValue[$key] = count($details[$key]);
2042 $form->assign_by_ref("{$prefix}viewCustomData", $details);
2048 * Get the custom group titles by custom field ids.
2050 * @param array $fieldIds
2051 * Array of custom field ids.
2053 * @return array|NULL
2054 * array consisting of groups and fields labels with ids.
2056 public static function getGroupTitles($fieldIds) {
2057 if (!is_array($fieldIds) && empty($fieldIds)) {
2062 $fIds = "(" . implode(',', $fieldIds) . ")";
2065 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2066 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2067 FROM civicrm_custom_group, civicrm_custom_field
2068 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2069 AND civicrm_custom_field.id IN {$fIds}";
2071 $dao = CRM_Core_DAO
::executeQuery($query);
2072 while ($dao->fetch()) {
2073 $groupLabels[$dao->fieldID
] = [
2074 'fieldID' => $dao->fieldID
,
2075 'fieldLabel' => $dao->fieldLabel
,
2076 'groupID' => $dao->groupID
,
2077 'groupTitle' => $dao->groupTitle
,
2081 return $groupLabels;
2084 public static function dropAllTables() {
2085 $query = "SELECT table_name FROM civicrm_custom_group";
2086 $dao = CRM_Core_DAO
::executeQuery($query);
2088 while ($dao->fetch()) {
2089 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2090 CRM_Core_DAO
::executeQuery($query);
2095 * Check whether custom group is empty or not.
2101 * true if empty otherwise false.
2103 public static function isGroupEmpty($gID) {
2108 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2113 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2114 $value = CRM_Core_DAO
::singleValueQuery($query);
2116 if (empty($value)) {
2124 * Get the list of types for objects that a custom group extends to.
2126 * @param array $types
2127 * Var which should have the list appended.
2131 * @throws \Exception
2133 public static function getExtendedObjectTypes(&$types = []) {
2134 static $flag = FALSE, $objTypes = [];
2138 CRM_Core_OptionValue
::getValues(['name' => 'cg_extend_objects'], $extendObjs);
2140 foreach ($extendObjs as $ovId => $ovValues) {
2141 if ($ovValues['description']) {
2142 // description is expected to be a callback func to subtypes
2143 list($callback, $args) = explode(';', trim($ovValues['description']));
2149 if (!is_array($args)) {
2150 CRM_Core_Error
::fatal('Arg is not of type array');
2153 list($className) = explode('::', $callback);
2154 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
2156 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2162 $types = array_merge($types, $objTypes);
2167 * @param int $customGroupId
2168 * @param int $entityId
2172 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2173 // check whether the group is multiple
2174 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2175 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2176 $hasReachedMax = FALSE;
2178 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2180 if (!$maxMultiple) {
2181 $hasReachedMax = FALSE;
2184 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2185 // count the number of entries for a entity
2186 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2187 $params = [1 => [$entityId, 'Integer']];
2188 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2190 if ($count >= $maxMultiple) {
2191 $hasReachedMax = TRUE;
2195 return $hasReachedMax;
2201 public static function getMultipleFieldGroup() {
2202 $multipleGroup = [];
2203 $dao = new CRM_Core_DAO_CustomGroup();
2204 $dao->is_multiple
= 1;
2205 $dao->is_active
= 1;
2207 while ($dao->fetch()) {
2208 $multipleGroup[$dao->id
] = $dao->title
;
2210 return $multipleGroup;