Merge pull request #15796 from seamuslee001/dev_core_183_requirements
[civicrm-core.git] / CRM / Core / BAO / CustomField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Business objects for managing custom data fields.
20 */
21 class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
22
23 /**
24 * Array to hold (formatted) fields for import
25 *
26 * @var array
27 */
28 public static $_importFields = NULL;
29
30 /**
31 * Build and retrieve the list of data types and descriptions.
32 *
33 * @return array
34 * Data type => Description
35 */
36 public static function dataType() {
37 return [
38 'String' => ts('Alphanumeric'),
39 'Int' => ts('Integer'),
40 'Float' => ts('Number'),
41 'Money' => ts('Money'),
42 'Memo' => ts('Note'),
43 'Date' => ts('Date'),
44 'Boolean' => ts('Yes or No'),
45 'StateProvince' => ts('State/Province'),
46 'Country' => ts('Country'),
47 'File' => ts('File'),
48 'Link' => ts('Link'),
49 'ContactReference' => ts('Contact Reference'),
50 ];
51 }
52
53 /**
54 * Build the map of custom field's data types and there respective Util type
55 *
56 * @return array
57 * Data data-type => CRM_Utils_Type
58 */
59 public static function dataToType() {
60 return [
61 'String' => CRM_Utils_Type::T_STRING,
62 'Int' => CRM_Utils_Type::T_INT,
63 'Money' => CRM_Utils_Type::T_MONEY,
64 'Memo' => CRM_Utils_Type::T_LONGTEXT,
65 'Float' => CRM_Utils_Type::T_FLOAT,
66 'Date' => CRM_Utils_Type::T_DATE,
67 'DateTime' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
68 'Boolean' => CRM_Utils_Type::T_BOOLEAN,
69 'StateProvince' => CRM_Utils_Type::T_INT,
70 'File' => CRM_Utils_Type::T_STRING,
71 'Link' => CRM_Utils_Type::T_STRING,
72 'ContactReference' => CRM_Utils_Type::T_INT,
73 'Country' => CRM_Utils_Type::T_INT,
74 ];
75 }
76
77 /**
78 * Takes an associative array and creates a custom field object.
79 *
80 * This function is invoked from within the web form layer and also from the api layer
81 *
82 * @param array $params
83 * (reference) an assoc array of name/value pairs.
84 *
85 * @return CRM_Core_DAO_CustomField
86 */
87 public static function create($params) {
88 $customField = self::createCustomFieldRecord($params);
89 $op = empty($params['id']) ? 'add' : 'modify';
90 self::createField($customField, $op);
91
92 CRM_Utils_Hook::post(($op === 'add' ? 'create' : 'edit'), 'CustomField', $customField->id, $customField);
93
94 CRM_Utils_System::flushCache();
95 // Flush caches is not aggressive about clearing the specific cache we know we want to clear
96 // so do it manually. Ideally we wouldn't need to clear others...
97 Civi::cache('metadata')->clear();
98
99 return $customField;
100 }
101
102 /**
103 * Create/ update several fields at once in a mysql efficient way.
104 *
105 * https://lab.civicrm.org/dev/core/issues/1093
106 *
107 * The intention is that apiv4 would expose any BAO with bulkSave as a new action.
108 *
109 * @param array $bulkParams
110 * Array of arrays as would be passed into create
111 * @param array $defaults
112 * Default parameters to be be merged into each of the params.
113 *
114 * @throws \CiviCRM_API3_Exception
115 */
116 public static function bulkSave($bulkParams, $defaults = []) {
117 $addedColumns = $sql = $tables = $customFields = [];
118 foreach ($bulkParams as $index => $fieldParams) {
119 $params = array_merge($defaults, $fieldParams);
120 $customField = self::createCustomFieldRecord($params);
121 $fieldSQL = self::getAlterFieldSQL($customField, empty($params['id']) ? 'add' : 'modify');
122 if (!isset($params['custom_group_id'])) {
123 $params['custom_group_id'] = civicrm_api3('CustomField', 'getvalue', ['id' => $customField->id, 'return' => 'custom_group_id']);
124 }
125 if (!isset($params['table_name'])) {
126 if (!isset($tables[$params['custom_group_id']])) {
127 $tables[$params['custom_group_id']] = civicrm_api3('CustomGroup', 'getvalue', [
128 'id' => $params['custom_group_id'],
129 'return' => 'table_name',
130 ]);
131 }
132 $params['table_name'] = $tables[$params['custom_group_id']];
133 }
134 $sql[$params['table_name']][] = $fieldSQL;
135 $addedColumns[$params['table_name']][] = $customField->name;
136 $customFields[$index] = $customField;
137 }
138
139 foreach ($sql as $tableName => $statements) {
140 // CRM-7007: do not i18n-rewrite this query
141 CRM_Core_DAO::executeQuery("ALTER TABLE $tableName " . implode(', ', $statements), [], TRUE, NULL, FALSE, FALSE);
142
143 if (CRM_Core_Config::singleton()->logging) {
144 $logging = new CRM_Logging_Schema();
145 $logging->fixSchemaDifferencesFor($tableName, ['ADD' => $addedColumns[$tableName]]);
146 }
147
148 Civi::service('sql_triggers')->rebuild($params['table_name'], TRUE);
149 }
150 CRM_Utils_System::flushCache();
151 foreach ($customFields as $index => $customField) {
152 CRM_Utils_Hook::post(empty($bulkParams[$index]['id']) ? 'create' : 'edit', 'CustomField', $customField->id, $customField);
153 }
154 }
155
156 /**
157 * Fetch object based on array of properties.
158 *
159 * @param array $params
160 * (reference ) an assoc array of name/value pairs.
161 * @param array $defaults
162 * (reference ) an assoc array to hold the flattened values.
163 *
164 * @return CRM_Core_DAO_CustomField
165 */
166 public static function retrieve(&$params, &$defaults) {
167 return CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
168 }
169
170 /**
171 * Update the is_active flag in the db.
172 *
173 * @param int $id
174 * Id of the database record.
175 * @param bool $is_active
176 * Value we want to set the is_active field.
177 *
178 * @return bool
179 * true if we found and updated the object, else false
180 */
181 public static function setIsActive($id, $is_active) {
182
183 CRM_Utils_System::flushCache();
184
185 //enable-disable CustomField
186 CRM_Core_BAO_UFField::setUFField($id, $is_active);
187 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
188 }
189
190 /**
191 * Get the field title.
192 *
193 * @param int $id
194 * Id of field.
195 *
196 * @return string
197 * name
198 */
199 public static function getTitle($id) {
200 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
201 }
202
203 /**
204 * @param string $context
205 * @return array|bool
206 */
207 public function getOptions($context = NULL) {
208 CRM_Core_DAO::buildOptionsContext($context);
209
210 if (!$this->id) {
211 return FALSE;
212 }
213 $cacheKey = "CRM_Core_BAO_CustomField_getOptions_{$this->id}_$context";
214 $cache = CRM_Utils_Cache::singleton();
215 $options = $cache->get($cacheKey);
216 if (!isset($options)) {
217 if (!$this->data_type || !$this->custom_group_id) {
218 $this->find(TRUE);
219 }
220
221 // This will hold the list of options in format key => label
222 $options = [];
223
224 if (!empty($this->option_group_id)) {
225 $options = CRM_Core_OptionGroup::valuesByID(
226 $this->option_group_id, FALSE, FALSE, FALSE, $context == 'validate' ? 'name' : 'label', !($context == 'validate' || $context == 'get')
227 );
228 }
229 elseif ($this->data_type === 'StateProvince') {
230 $options = CRM_Core_PseudoConstant::stateProvince();
231 }
232 elseif ($this->data_type === 'Country') {
233 $options = $context == 'validate' ? CRM_Core_PseudoConstant::countryIsoCode() : CRM_Core_PseudoConstant::country();
234 }
235 elseif ($this->data_type === 'Boolean') {
236 $options = $context == 'validate' ? [0, 1] : CRM_Core_SelectValues::boolean();
237 }
238 CRM_Utils_Hook::customFieldOptions($this->id, $options, FALSE);
239 CRM_Utils_Hook::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, ['context' => $context]);
240 $cache->set($cacheKey, $options);
241 }
242 return $options;
243 }
244
245 /**
246 * @inheritDoc
247 */
248 public static function buildOptions($fieldName, $context = NULL, $props = []) {
249 $options = parent::buildOptions($fieldName, $context, $props);
250 // This provides legacy support for APIv3, allowing no-longer-existent html types
251 if ($fieldName == 'html_type' && isset($props['version']) && $props['version'] == 3) {
252 $options['Multi-Select'] = 'Multi-Select';
253 $options['Multi-Select Country'] = 'Multi-Select Country';
254 $options['Multi-Select State/Province'] = 'Multi-Select State/Province';
255 }
256 return $options;
257 }
258
259 /**
260 * Store and return an array of all active custom fields.
261 *
262 * @param string $customDataType
263 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
264 * @param bool $showAll
265 * If true returns all fields (includes disabled fields).
266 * @param bool $inline
267 * If true returns all inline fields (includes disabled fields).
268 * @param int $customDataSubType
269 * Custom Data sub type value.
270 * @param int $customDataSubName
271 * Custom Data sub name value.
272 * @param bool $onlyParent
273 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
274 * @param bool $onlySubType
275 * Return only custom data for subtype.
276 * @param bool $checkPermission
277 * If false, do not include permissioning clause.
278 *
279 * @return array
280 * an array of active custom fields.
281 */
282 public static function &getFields(
283 $customDataType = 'Individual',
284 $showAll = FALSE,
285 $inline = FALSE,
286 $customDataSubType = NULL,
287 $customDataSubName = NULL,
288 $onlyParent = FALSE,
289 $onlySubType = FALSE,
290 $checkPermission = TRUE
291 ) {
292 if (empty($customDataType)) {
293 $customDataType = ['Contact', 'Individual', 'Organization', 'Household'];
294 }
295 if ($customDataType === 'ANY') {
296 // NULL should have been respected but the line above broke that.
297 // boo for us not having enough unit tests back them.
298 $customDataType = NULL;
299 }
300 if ($customDataType && !is_array($customDataType)) {
301
302 if (in_array($customDataType, CRM_Contact_BAO_ContactType::subTypes())) {
303 // This is the case when getFieldsForImport() requires fields
304 // limited strictly to a subtype.
305 $customDataSubType = $customDataType;
306 $customDataType = CRM_Contact_BAO_ContactType::getBasicType($customDataType);
307 $onlySubType = TRUE;
308 }
309
310 if (in_array($customDataType, array_keys(CRM_Core_SelectValues::customGroupExtends()))) {
311 // this makes the method flexible to support retrieving fields
312 // for multiple extends value.
313 $customDataType = [$customDataType];
314 }
315 }
316
317 $customDataSubType = CRM_Utils_Array::explodePadded($customDataSubType);
318
319 if (is_array($customDataType)) {
320 $cacheKey = implode('_', $customDataType);
321 }
322 else {
323 $cacheKey = $customDataType;
324 }
325
326 $cacheKey .= !empty($customDataSubType) ? ('_' . implode('_', $customDataSubType)) : '_0';
327 $cacheKey .= $customDataSubName ? "{$customDataSubName}_" : '_0';
328 $cacheKey .= $showAll ? '_1' : '_0';
329 $cacheKey .= $inline ? '_1_' : '_0_';
330 $cacheKey .= $onlyParent ? '_1_' : '_0_';
331 $cacheKey .= $onlySubType ? '_1_' : '_0_';
332 $cacheKey .= $checkPermission ? '_1_' : '_0_';
333 $cacheKey .= '_' . CRM_Core_Config::domainID() . '_';
334
335 $cgTable = CRM_Core_DAO_CustomGroup::getTableName();
336
337 // also get the permission stuff here
338 if ($checkPermission) {
339 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
340 "{$cgTable}."
341 );
342 }
343 else {
344 $permissionClause = '(1)';
345 }
346
347 // lets md5 permission clause and take first 8 characters
348 $cacheKey .= substr(md5($permissionClause), 0, 8);
349
350 if (strlen($cacheKey) > 40) {
351 $cacheKey = md5($cacheKey);
352 }
353
354 if (!self::$_importFields ||
355 CRM_Utils_Array::value($cacheKey, self::$_importFields) === NULL
356 ) {
357 if (!self::$_importFields) {
358 self::$_importFields = [];
359 }
360
361 // check if we can retrieve from database cache
362 $fields = Civi::Cache('fields')->get("custom importableFields $cacheKey");
363
364 if ($fields === NULL) {
365 $cfTable = self::getTableName();
366
367 $extends = '';
368 if (is_array($customDataType)) {
369 $value = NULL;
370 foreach ($customDataType as $dataType) {
371 if (in_array($dataType, array_keys(CRM_Core_SelectValues::customGroupExtends()))) {
372 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
373 $val = "'" . CRM_Utils_Type::escape($dataType, 'String') . "', 'Contact' ";
374 }
375 else {
376 $val = "'" . CRM_Utils_Type::escape($dataType, 'String') . "'";
377 }
378 $value = $value ? $value . ", {$val}" : $val;
379 }
380 }
381 if ($value) {
382 $extends = "AND $cgTable.extends IN ( $value ) ";
383 }
384 }
385
386 if (!empty($customDataType) && empty($extends)) {
387 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
388 self::$_importFields[$cacheKey] = [];
389 return self::$_importFields[$cacheKey];
390 }
391
392 if ($onlyParent) {
393 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
394 }
395
396 $query = "SELECT $cfTable.id, $cfTable.label,
397 $cgTable.title,
398 $cfTable.data_type,
399 $cfTable.html_type,
400 $cfTable.default_value,
401 $cfTable.options_per_line, $cfTable.text_length,
402 $cfTable.custom_group_id,
403 $cfTable.is_required,
404 $cfTable.column_name,
405 $cgTable.extends, $cfTable.is_search_range,
406 $cgTable.extends_entity_column_value,
407 $cgTable.extends_entity_column_id,
408 $cfTable.is_view,
409 $cfTable.option_group_id,
410 $cfTable.date_format,
411 $cfTable.time_format,
412 $cgTable.is_multiple,
413 $cfTable.serialize,
414 $cgTable.table_name,
415 og.name as option_group_name
416 FROM $cfTable
417 INNER JOIN $cgTable
418 ON $cfTable.custom_group_id = $cgTable.id
419 LEFT JOIN civicrm_option_group og
420 ON $cfTable.option_group_id = og.id
421 WHERE ( 1 ) ";
422
423 if (!$showAll) {
424 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
425 }
426
427 if ($inline) {
428 $query .= " AND $cgTable.style = 'Inline' ";
429 }
430
431 //get the custom fields for specific type in
432 //combination with fields those support any type.
433 if (!empty($customDataSubType)) {
434 $subtypeClause = [];
435 foreach ($customDataSubType as $subtype) {
436 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($subtype, 'String') . CRM_Core_DAO::VALUE_SEPARATOR;
437 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
438 }
439 if (!$onlySubType) {
440 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
441 }
442 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
443 }
444
445 if ($customDataSubName) {
446 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
447 }
448
449 // also get the permission stuff here
450 if ($checkPermission) {
451 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
452 "{$cgTable}.", TRUE
453 );
454 }
455 else {
456 $permissionClause = '(1)';
457 }
458
459 $query .= " $extends AND $permissionClause
460 ORDER BY $cgTable.weight, $cgTable.title,
461 $cfTable.weight, $cfTable.label";
462
463 $dao = CRM_Core_DAO::executeQuery($query);
464
465 $fields = [];
466 while (($dao->fetch()) != NULL) {
467 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
468 $fields[$dao->id]['id'] = $dao->id;
469 $fields[$dao->id]['label'] = $dao->label;
470 // This seems broken, but not in a new way.
471 $fields[$dao->id]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
472 // To support the consolidation of various functions & their expectations.
473 $fields[$dao->id]['title'] = $dao->label;
474 $fields[$dao->id]['custom_field_id'] = $dao->id;
475 $fields[$dao->id]['groupTitle'] = $dao->title;
476 $fields[$dao->id]['data_type'] = $dao->data_type;
477 $fields[$dao->id]['name'] = 'custom_' . $dao->id;
478 $fields[$dao->id]['type'] = CRM_Utils_Array::value($dao->data_type, self::dataToType());
479 $fields[$dao->id]['html_type'] = $dao->html_type;
480 $fields[$dao->id]['default_value'] = $dao->default_value;
481 $fields[$dao->id]['text_length'] = $dao->text_length;
482 $fields[$dao->id]['options_per_line'] = $dao->options_per_line;
483 $fields[$dao->id]['custom_group_id'] = $dao->custom_group_id;
484 $fields[$dao->id]['extends'] = $dao->extends;
485 $fields[$dao->id]['is_search_range'] = $dao->is_search_range;
486 $fields[$dao->id]['extends_entity_column_value'] = $dao->extends_entity_column_value;
487 $fields[$dao->id]['extends_entity_column_id'] = $dao->extends_entity_column_id;
488 $fields[$dao->id]['is_view'] = $dao->is_view;
489 $fields[$dao->id]['is_multiple'] = $dao->is_multiple;
490 $fields[$dao->id]['option_group_id'] = $dao->option_group_id;
491 $fields[$dao->id]['date_format'] = $dao->date_format;
492 $fields[$dao->id]['time_format'] = $dao->time_format;
493 $fields[$dao->id]['is_required'] = $dao->is_required;
494 $fields[$dao->id]['table_name'] = $dao->table_name;
495 $fields[$dao->id]['column_name'] = $dao->column_name;
496 $fields[$dao->id]['serialize'] = $dao->serialize;
497 $fields[$dao->id]['where'] = $dao->table_name . '.' . $dao->column_name;
498 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
499 $fields[$dao->id]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery::$extendsMap) ? CRM_Core_BAO_CustomQuery::$extendsMap[$dao->extends] : '';
500 if (in_array($dao->extends, CRM_Contact_BAO_ContactType::subTypes())) {
501 // if $extends is a subtype, refer contact table
502 $fields[$dao->id]['extends_table'] = 'civicrm_contact';
503 }
504 // Search table is used by query object searches..
505 $fields[$dao->id]['search_table'] = ($fields[$dao->id]['extends_table'] == 'civicrm_contact') ? 'contact_a' : $fields[$dao->id]['extends_table'];
506 self::getOptionsForField($fields[$dao->id], $dao->option_group_name);
507 }
508
509 Civi::cache('fields')->set("custom importableFields $cacheKey", $fields);
510 }
511 self::$_importFields[$cacheKey] = $fields;
512 }
513
514 return self::$_importFields[$cacheKey];
515 }
516
517 /**
518 * Return the field ids and names (with groups) for import purpose.
519 *
520 * @param int|string $contactType Contact type
521 * @param bool $showAll
522 * If true returns all fields (includes disabled fields).
523 * @param bool $onlyParent
524 * Return fields ONLY related to basic types.
525 * @param bool $search
526 * When called from search and multiple records need to be returned.
527 * @param bool $checkPermission
528 * If false, do not include permissioning clause.
529 *
530 * @param bool $withMultiple
531 *
532 * @return array
533 */
534 public static function getFieldsForImport(
535 $contactType = 'Individual',
536 $showAll = FALSE,
537 $onlyParent = FALSE,
538 $search = FALSE,
539 $checkPermission = TRUE,
540 $withMultiple = FALSE
541 ) {
542 // Note: there are situations when we want getFieldsForImport() return fields related
543 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
544 $fields = &self::getFields($contactType,
545 $showAll,
546 FALSE,
547 NULL,
548 NULL,
549 $onlyParent,
550 FALSE,
551 $checkPermission
552 );
553
554 $importableFields = [];
555 foreach ($fields as $id => $values) {
556 // for now we should not allow multiple fields in profile / export etc, hence unsetting
557 if (!$search &&
558 (!empty($values['is_multiple']) && !$withMultiple)
559 ) {
560 continue;
561 }
562 if (!empty($values['text_length'])) {
563 $values['maxlength'] = (int) $values['text_length'];
564 }
565
566 /* generate the key for the fields array */
567
568 $key = "custom_$id";
569 $importableFields[$key] = $values;
570 $importableFields[$key]['import'] = 1;
571 }
572
573 return $importableFields;
574 }
575
576 /**
577 * Get the field id from an import key.
578 *
579 * @param string $key
580 * The key to parse.
581 *
582 * @param bool $all
583 *
584 * @return int|null
585 * The id (if exists)
586 */
587 public static function getKeyID($key, $all = FALSE) {
588 $match = [];
589 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
590 if (!$all) {
591 return $match[1];
592 }
593 else {
594 return [
595 $match[1],
596 CRM_Utils_Array::value(2, $match),
597 ];
598 }
599 }
600 return $all ? [NULL, NULL] : NULL;
601 }
602
603 /**
604 * Use the cache to get all values of a specific custom field.
605 *
606 * @param int $fieldID
607 * The custom field ID.
608 *
609 * @return CRM_Core_BAO_CustomField
610 * The field object.
611 * @throws CRM_Core_Exception
612 */
613 public static function getFieldObject($fieldID) {
614 $field = new CRM_Core_BAO_CustomField();
615
616 // check if we can get the field values from the system cache
617 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
618 $cache = CRM_Utils_Cache::singleton();
619 $fieldValues = $cache->get($cacheKey);
620 if (empty($fieldValues)) {
621 $field->id = $fieldID;
622 if (!$field->find(TRUE)) {
623 throw new CRM_Core_Exception('Cannot find Custom Field');
624 }
625
626 $fieldValues = [];
627 CRM_Core_DAO::storeValues($field, $fieldValues);
628
629 $cache->set($cacheKey, $fieldValues);
630 }
631 else {
632 $field->copyValues($fieldValues);
633 }
634
635 return $field;
636 }
637
638 /**
639 * Add a custom field to an existing form.
640 *
641 * @param CRM_Core_Form $qf
642 * Form object (reference).
643 * @param string $elementName
644 * Name of the custom field.
645 * @param int $fieldId
646 * @param bool $useRequired
647 * True if required else false.
648 * @param bool $search
649 * True if used for search else false.
650 * @param string $label
651 * Label for custom field.
652 * @return \HTML_QuickForm_Element|null
653 * @throws \CiviCRM_API3_Exception
654 */
655 public static function addQuickFormElement(
656 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
657 ) {
658 $field = self::getFieldObject($fieldId);
659 $widget = $field->html_type;
660 $element = NULL;
661 $customFieldAttributes = [];
662
663 // Custom field HTML should indicate group+field name
664 $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
665 $dataCrmCustomVal = $groupName . ':' . $field->name;
666 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
667 $field->attributes .= $dataCrmCustomAttr;
668
669 // Fixed for Issue CRM-2183
670 if ($widget == 'TextArea' && $search) {
671 $widget = 'Text';
672 }
673
674 $placeholder = $search ? ts('- any -') : ($useRequired ? ts('- select -') : ts('- none -'));
675
676 // FIXME: Why are select state/country separate widget types?
677 $isSelect = (in_array($widget, [
678 'Select',
679 'Select State/Province',
680 'Select Country',
681 'CheckBox',
682 'Radio',
683 ]));
684
685 if ($isSelect) {
686 $options = $field->getOptions($search ? 'search' : 'create');
687
688 // Consolidate widget types to simplify the below switch statement
689 if ($search || (strpos($widget, 'Select') !== FALSE)) {
690 $widget = 'Select';
691 }
692
693 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
694 $selectAttributes = ['class' => 'crm-select2'];
695
696 // Search field is always multi-select
697 if ($search || (self::isSerialized($field) && $widget === 'Select')) {
698 $selectAttributes['class'] .= ' huge';
699 $selectAttributes['multiple'] = 'multiple';
700 $selectAttributes['placeholder'] = $placeholder;
701 }
702
703 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
704 $canEditOptions = CRM_Core_Permission::check('administer CiviCRM');
705 if ($field->option_group_id && !$search && $isSelect && $canEditOptions) {
706 $customFieldAttributes += [
707 'data-api-entity' => $field->getEntity(),
708 'data-api-field' => 'custom_' . $field->id,
709 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id),
710 ];
711 $selectAttributes += $customFieldAttributes;
712 }
713 }
714
715 $rangeDataTypes = ['Int', 'Float', 'Money'];
716
717 if (!isset($label)) {
718 $label = $field->label;
719 }
720
721 // at some point in time we might want to split the below into small functions
722
723 switch ($widget) {
724 case 'Text':
725 case 'Link':
726 if ($field->is_search_range && $search && in_array($field->data_type, $rangeDataTypes)) {
727 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
728 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
729 }
730 else {
731 if ($field->text_length) {
732 $field->attributes .= ' maxlength=' . $field->text_length;
733 if ($field->text_length < 20) {
734 $field->attributes .= ' size=' . $field->text_length;
735 }
736 }
737 $element = $qf->add('text', $elementName, $label,
738 $field->attributes,
739 $useRequired && !$search
740 );
741 }
742 break;
743
744 case 'TextArea':
745 $attributes = $dataCrmCustomAttr;
746 if ($field->note_rows) {
747 $attributes .= 'rows=' . $field->note_rows;
748 }
749 else {
750 $attributes .= 'rows=4';
751 }
752 if ($field->note_columns) {
753 $attributes .= ' cols=' . $field->note_columns;
754 }
755 else {
756 $attributes .= ' cols=60';
757 }
758 if ($field->text_length) {
759 $attributes .= ' maxlength=' . $field->text_length;
760 }
761 $element = $qf->add('textarea',
762 $elementName,
763 $label,
764 $attributes,
765 $useRequired && !$search
766 );
767 break;
768
769 case 'Select Date':
770 $attr = ['data-crm-custom' => $dataCrmCustomVal];
771 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
772 $minYear = isset($field->start_date_years) ? (date('Y') - $field->start_date_years) : NULL;
773 $maxYear = isset($field->end_date_years) ? (date('Y') + $field->end_date_years) : NULL;
774
775 $params = [
776 'date' => $field->date_format,
777 'minDate' => isset($minYear) ? $minYear . '-01-01' : NULL,
778 //CRM-18487 - max date should be the last date of the year.
779 'maxDate' => isset($maxYear) ? $maxYear . '-12-31' : NULL,
780 'time' => $field->time_format ? $field->time_format * 12 : FALSE,
781 ];
782 if ($field->is_search_range && $search) {
783 $qf->add('datepicker', $elementName . '_from', $label, $attr + array('placeholder' => ts('From')), FALSE, $params);
784 $qf->add('datepicker', $elementName . '_to', NULL, $attr + array('placeholder' => ts('To')), FALSE, $params);
785 }
786 else {
787 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
788 }
789 break;
790
791 case 'Radio':
792 if ($field->is_search_range && $search && in_array($field->data_type, $rangeDataTypes)) {
793 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
794 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
795 }
796 else {
797 $choice = [];
798 parse_str($field->attributes, $radioAttributes);
799 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
800
801 foreach ($options as $v => $l) {
802 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
803 }
804 $element = $qf->addGroup($choice, $elementName, $label);
805 $optionEditKey = 'data-option-edit-path';
806 if (isset($selectAttributes[$optionEditKey])) {
807 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
808 }
809
810 if ($useRequired && !$search) {
811 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
812 }
813 else {
814 $element->setAttribute('allowClear', TRUE);
815 }
816 }
817 break;
818
819 // For all select elements
820 case 'Select':
821 if ($field->is_search_range && $search && in_array($field->data_type, $rangeDataTypes)) {
822 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
823 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
824 }
825 else {
826 if (empty($selectAttributes['multiple'])) {
827 $options = ['' => $placeholder] + $options;
828 }
829 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
830
831 // Add and/or option for fields that store multiple values
832 if ($search && self::isSerialized($field)) {
833
834 $operators = [
835 $qf->createElement('radio', NULL, '', ts('Any'), 'or', ['title' => ts('Results may contain any of the selected options')]),
836 $qf->createElement('radio', NULL, '', ts('All'), 'and', ['title' => ts('Results must have all of the selected options')]),
837 ];
838 $qf->addGroup($operators, $elementName . '_operator');
839 $qf->setDefaults([$elementName . '_operator' => 'or']);
840 }
841 }
842 break;
843
844 case 'CheckBox':
845 $check = [];
846 foreach ($options as $v => $l) {
847 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
848 }
849
850 $group = $element = $qf->addGroup($check, $elementName, $label);
851 $optionEditKey = 'data-option-edit-path';
852 if (isset($customFieldAttributes[$optionEditKey])) {
853 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
854 }
855
856 if ($useRequired && !$search) {
857 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
858 }
859 break;
860
861 case 'File':
862 // we should not build upload file in search mode
863 if ($search) {
864 return NULL;
865 }
866 $element = $qf->add(
867 strtolower($field->html_type),
868 $elementName,
869 $label,
870 $field->attributes,
871 $useRequired && !$search
872 );
873 $qf->addUploadElement($elementName);
874 break;
875
876 case 'RichTextEditor':
877 $attributes = [
878 'rows' => $field->note_rows,
879 'cols' => $field->note_columns,
880 'data-crm-custom' => $dataCrmCustomVal,
881 ];
882 if ($field->text_length) {
883 $attributes['maxlength'] = $field->text_length;
884 }
885 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
886 break;
887
888 case 'Autocomplete-Select':
889 static $customUrls = [];
890 // Fixme: why is this a string in the first place??
891 $attributes = [];
892 if ($field->attributes) {
893 foreach (explode(' ', $field->attributes) as $at) {
894 if (strpos($at, '=')) {
895 list($k, $v) = explode('=', $at);
896 $attributes[$k] = trim($v, ' "');
897 }
898 }
899 }
900 if ($field->data_type == 'ContactReference') {
901 // break if contact does not have permission to access ContactReference
902 if (!CRM_Core_Permission::check('access contact reference fields')) {
903 break;
904 }
905 $attributes['class'] = (isset($attributes['class']) ? $attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
906 $attributes['data-api-entity'] = 'Contact';
907 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
908
909 $urlParams = "context=customfield&id={$field->id}";
910 $idOfelement = $elementName;
911 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
912 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
913 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
914 // rather than layering on more hacks.
915 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
916 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') + 1)), 0, -1);
917 }
918 $customUrls[$idOfelement] = CRM_Utils_System::url('civicrm/ajax/contactref',
919 $urlParams,
920 FALSE, NULL, FALSE
921 );
922
923 }
924 else {
925 // FIXME: This won't work with customFieldOptions hook
926 $attributes += [
927 'entity' => 'OptionValue',
928 'placeholder' => $placeholder,
929 'multiple' => $search,
930 'api' => [
931 'params' => ['option_group_id' => $field->option_group_id, 'is_active' => 1],
932 ],
933 ];
934 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
935 }
936
937 $qf->assign('customUrls', $customUrls);
938 break;
939 }
940
941 switch ($field->data_type) {
942 case 'Int':
943 // integers will have numeric rule applied to them.
944 if ($field->is_search_range && $search) {
945 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', [1 => $label]), 'integer');
946 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', [1 => $label]), 'integer');
947 }
948 elseif ($widget == 'Text') {
949 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', [1 => $label]), 'integer');
950 }
951 break;
952
953 case 'Float':
954 if ($field->is_search_range && $search) {
955 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', [1 => $label]), 'numeric');
956 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', [1 => $label]), 'numeric');
957 }
958 elseif ($widget == 'Text') {
959 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', [1 => $label]), 'numeric');
960 }
961 break;
962
963 case 'Money':
964 if ($field->is_search_range && $search) {
965 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
966 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
967 }
968 elseif ($widget == 'Text') {
969 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
970 }
971 break;
972
973 case 'Link':
974 $element->setAttribute('class', "url");
975 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
976 break;
977 }
978 if ($field->is_view && !$search) {
979 $qf->freeze($elementName);
980 }
981 return $element;
982 }
983
984 /**
985 * Delete the Custom Field.
986 *
987 * @param object $field
988 * The field object.
989 */
990 public static function deleteField($field) {
991 CRM_Utils_System::flushCache();
992
993 // first delete the custom option group and values associated with this field
994 if ($field->option_group_id) {
995 //check if option group is related to any other field, if
996 //not delete the option group and related option values
997 self::checkOptionGroup($field->option_group_id);
998 }
999
1000 // next drop the column from the custom value table
1001 self::createField($field, 'delete');
1002
1003 $field->delete();
1004 CRM_Core_BAO_UFField::delUFField($field->id);
1005 CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1006
1007 CRM_Utils_Hook::post('delete', 'CustomField', $field->id, $field);
1008 }
1009
1010 /**
1011 * @param string|int|array|null $value
1012 * @param CRM_Core_BAO_CustomField|int|array|string $field
1013 * @param int $entityId
1014 *
1015 * @return string
1016 *
1017 * @throws \CRM_Core_Exception
1018 */
1019 public static function displayValue($value, $field, $entityId = NULL) {
1020 $field = is_array($field) ? $field['id'] : $field;
1021 $fieldId = is_object($field) ? $field->id : (int) str_replace('custom_', '', $field);
1022
1023 if (!$fieldId) {
1024 throw new CRM_Core_Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1025 }
1026
1027 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1028 $field = self::getFieldObject($fieldId);
1029 }
1030
1031 $fieldInfo = ['options' => $field->getOptions()] + (array) $field;
1032
1033 $displayValue = self::formatDisplayValue($value, $fieldInfo, $entityId);
1034
1035 // Call hook to alter display value.
1036 CRM_Utils_Hook::alterCustomFieldDisplayValue($displayValue, $value, $entityId, $fieldInfo);
1037
1038 return $displayValue;
1039 }
1040
1041 /**
1042 * Lower-level logic for rendering a custom field value
1043 *
1044 * @param string|array $value
1045 * @param array $field
1046 * @param int|null $entityId
1047 *
1048 * @return string
1049 */
1050 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1051
1052 if (self::isSerialized($field) && !is_array($value)) {
1053 $value = CRM_Utils_Array::explodePadded($value);
1054 }
1055 // CRM-12989 fix
1056 if ($field['html_type'] == 'CheckBox' && $value) {
1057 $value = CRM_Utils_Array::convertCheckboxFormatToArray($value);
1058 }
1059
1060 $display = is_array($value) ? implode(', ', $value) : (string) $value;
1061
1062 switch ($field['html_type']) {
1063
1064 case 'Select':
1065 case 'Autocomplete-Select':
1066 case 'Radio':
1067 case 'Select Country':
1068 case 'Select State/Province':
1069 case 'CheckBox':
1070 if ($field['data_type'] == 'ContactReference' && $value) {
1071 if (is_numeric($value)) {
1072 $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1073 }
1074 else {
1075 $display = $value;
1076 }
1077 }
1078 elseif (is_array($value)) {
1079 $v = [];
1080 foreach ($value as $key => $val) {
1081 $v[] = $field['options'][$val] ?? NULL;
1082 }
1083 $display = implode(', ', $v);
1084 }
1085 else {
1086 $display = CRM_Utils_Array::value($value, $field['options'], '');
1087 }
1088 break;
1089
1090 case 'Select Date':
1091 $customFormat = NULL;
1092
1093 // FIXME: Are there any legitimate reasons why $value would be an array?
1094 // Or should we throw an exception here if it is?
1095 $value = is_array($value) ? CRM_Utils_Array::first($value) : $value;
1096
1097 $actualPHPFormats = CRM_Utils_Date::datePluginToPHPFormats();
1098 $format = $field['date_format'] ?? NULL;
1099
1100 if ($format) {
1101 if (array_key_exists($format, $actualPHPFormats)) {
1102 $customTimeFormat = (array) $actualPHPFormats[$format];
1103 switch (CRM_Utils_Array::value('time_format', $field)) {
1104 case 1:
1105 $customTimeFormat[] = 'g:iA';
1106 break;
1107
1108 case 2:
1109 $customTimeFormat[] = 'G:i';
1110 break;
1111
1112 default:
1113 //If time is not selected remove time from value.
1114 $value = $value ? date('Y-m-d', strtotime($value)) : '';
1115 }
1116 $customFormat = implode(" ", $customTimeFormat);
1117 }
1118 }
1119 $display = CRM_Utils_Date::processDate($value, NULL, FALSE, $customFormat);
1120 break;
1121
1122 case 'File':
1123 // In the context of displaying a profile, show file/image
1124 if ($value) {
1125 if ($entityId) {
1126 if (CRM_Utils_Rule::positiveInteger($value)) {
1127 $fileId = $value;
1128 }
1129 else {
1130 $fileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1131 }
1132 $url = self::getFileURL($entityId, $field['id'], $fileId);
1133 if ($url) {
1134 $display = $url['file_url'];
1135 }
1136 }
1137 else {
1138 // In other contexts show a paperclip icon
1139 if (CRM_Utils_Rule::integer($value)) {
1140 $icons = CRM_Core_BAO_File::paperIconAttachment('*', $value);
1141
1142 $file_description = '';
1143 try {
1144 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1145 }
1146 catch (CiviCRM_API3_Exception $dontcare) {
1147 // don't care
1148 }
1149
1150 $display = "{$icons[$value]}{$file_description}";
1151 }
1152 else {
1153 //CRM-18396, if filename is passed instead
1154 $display = $value;
1155 }
1156 }
1157 }
1158 break;
1159
1160 case 'Link':
1161 $display = $display ? "<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1162 break;
1163
1164 case 'TextArea':
1165 $display = nl2br($display);
1166 break;
1167
1168 case 'Text':
1169 if ($field['data_type'] == 'Money' && isset($value)) {
1170 // $value can also be an array(while using IN operator from search builder or api).
1171 foreach ((array) $value as $val) {
1172 $disp[] = CRM_Utils_Money::format($val, NULL, NULL, TRUE);
1173 }
1174 $display = implode(', ', $disp);
1175 }
1176 break;
1177 }
1178 return $display;
1179 }
1180
1181 /**
1182 * Set default values for custom data used in profile.
1183 *
1184 * @param int $customFieldId
1185 * Custom field id.
1186 * @param string $elementName
1187 * Custom field name.
1188 * @param array $defaults
1189 * Associated array of fields.
1190 * @param int $contactId
1191 * Contact id.
1192 * @param int $mode
1193 * Profile mode.
1194 * @param mixed $value
1195 * If passed - dont fetch value from db,.
1196 * just format the given value
1197 */
1198 public static function setProfileDefaults(
1199 $customFieldId,
1200 $elementName,
1201 &$defaults,
1202 $contactId = NULL,
1203 $mode = NULL,
1204 $value = NULL
1205 ) {
1206 //get the type of custom field
1207 $customField = new CRM_Core_BAO_CustomField();
1208 $customField->id = $customFieldId;
1209 $customField->find(TRUE);
1210
1211 if (!$contactId) {
1212 if ($mode == CRM_Profile_Form::MODE_CREATE) {
1213 $value = $customField->default_value;
1214 }
1215 }
1216 else {
1217 if (!isset($value)) {
1218 $info = self::getTableColumnGroup($customFieldId);
1219 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1220 $result = CRM_Core_DAO::executeQuery($query);
1221 if ($result->fetch()) {
1222 $value = $result->value;
1223 }
1224 }
1225
1226 if ($customField->data_type == 'Country') {
1227 if (!$value) {
1228 $config = CRM_Core_Config::singleton();
1229 if ($config->defaultContactCountry) {
1230 $value = CRM_Core_BAO_Country::defaultContactCountry();
1231 }
1232 }
1233 }
1234 }
1235
1236 //set defaults if mode is registration
1237 if (!trim($value) &&
1238 ($value !== 0) &&
1239 (!in_array($mode, [CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH]))
1240 ) {
1241 $value = $customField->default_value;
1242 }
1243
1244 if ($customField->data_type == 'Money' && isset($value)) {
1245 $value = number_format($value, 2);
1246 }
1247 if (self::isSerialized($customField) && $value) {
1248 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
1249 $defaults[$elementName] = [];
1250 $checkedValue = CRM_Utils_Array::explodePadded($value);
1251 foreach ($customOption as $val) {
1252 if (in_array($val['value'], $checkedValue)) {
1253 if ($customField->html_type == 'CheckBox') {
1254 $defaults[$elementName][$val['value']] = 1;
1255 }
1256 else {
1257 $defaults[$elementName][$val['value']] = $val['value'];
1258 }
1259 }
1260 }
1261 }
1262 else {
1263 $defaults[$elementName] = $value;
1264 }
1265 }
1266
1267 /**
1268 * Get file url.
1269 *
1270 * @param int $contactID
1271 * @param int $cfID
1272 * @param int $fileID
1273 * @param bool $absolute
1274 *
1275 * @param string $multiRecordWhereClause
1276 *
1277 * @return array
1278 */
1279 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1280 if ($contactID) {
1281 if (!$fileID) {
1282 $params = ['id' => $cfID];
1283 $defaults = [];
1284 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1285 $columnName = $defaults['column_name'];
1286
1287 //table name of custom data
1288 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1289 $defaults['custom_group_id'],
1290 'table_name', 'id'
1291 );
1292
1293 //query to fetch id from civicrm_file
1294 if ($multiRecordWhereClause) {
1295 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1296 }
1297 else {
1298 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1299 }
1300 $fileID = CRM_Core_DAO::singleValueQuery($query);
1301 }
1302
1303 $result = [];
1304 if ($fileID) {
1305 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1306 $fileID,
1307 'mime_type',
1308 'id'
1309 );
1310 $result['file_id'] = $fileID;
1311
1312 if ($fileType == 'image/jpeg' ||
1313 $fileType == 'image/pjpeg' ||
1314 $fileType == 'image/gif' ||
1315 $fileType == 'image/x-png' ||
1316 $fileType == 'image/png'
1317 ) {
1318 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1319 $fileID,
1320 'entity_id',
1321 'file_id'
1322 );
1323 list($path) = CRM_Core_BAO_File::path($fileID, $entityId);
1324 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileID);
1325 $url = CRM_Utils_System::url('civicrm/file',
1326 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1327 $absolute, NULL, TRUE, TRUE
1328 );
1329 $result['file_url'] = CRM_Utils_File::getFileURL($path, $fileType, $url);
1330 }
1331 // for non image files
1332 else {
1333 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1334 $fileID,
1335 'uri'
1336 );
1337 $fileHash = CRM_Core_BAO_File::generateFileHash($contactID, $fileID);
1338 $url = CRM_Utils_System::url('civicrm/file',
1339 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1340 $absolute, NULL, TRUE, TRUE
1341 );
1342 $result['file_url'] = CRM_Utils_File::getFileURL($uri, $fileType, $url);
1343 }
1344 }
1345 return $result;
1346 }
1347 }
1348
1349 /**
1350 * Format custom fields before inserting.
1351 *
1352 * @param int $customFieldId
1353 * Custom field id.
1354 * @param array $customFormatted
1355 * Formatted array.
1356 * @param mixed $value
1357 * Value of custom field.
1358 * @param string $customFieldExtend
1359 * Custom field extends.
1360 * @param int $customValueId
1361 * Custom option value id.
1362 * @param int $entityId
1363 * Entity id (contribution, membership...).
1364 * @param bool $inline
1365 * Consider inline custom groups only.
1366 * @param bool $checkPermission
1367 * If false, do not include permissioning clause.
1368 * @param bool $includeViewOnly
1369 * If true, fields marked 'View Only' are included. Required for APIv3.
1370 *
1371 * @return array|NULL
1372 * formatted custom field array
1373 */
1374 public static function formatCustomField(
1375 $customFieldId, &$customFormatted, $value,
1376 $customFieldExtend, $customValueId = NULL,
1377 $entityId = NULL,
1378 $inline = FALSE,
1379 $checkPermission = TRUE,
1380 $includeViewOnly = FALSE
1381 ) {
1382 //get the custom fields for the entity
1383 //subtype and basic type
1384 $customDataSubType = NULL;
1385 if ($customFieldExtend) {
1386 // This is the case when getFieldsForImport() requires fields
1387 // of subtype and its parent.CRM-5143
1388 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1389 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType::subTypes(), (array) $customFieldExtend);
1390 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1391 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1392 if (is_array($customFieldExtend)) {
1393 $customFieldExtend = array_unique(array_values($customFieldExtend));
1394 }
1395 }
1396 }
1397
1398 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1399 FALSE,
1400 $inline,
1401 $customDataSubType,
1402 NULL,
1403 FALSE,
1404 FALSE,
1405 $checkPermission
1406 );
1407
1408 if (!array_key_exists($customFieldId, $customFields)) {
1409 return NULL;
1410 }
1411
1412 // return if field is a 'code' field
1413 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1414 return NULL;
1415 }
1416
1417 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1418
1419 if (!$customValueId &&
1420 // we always create new entites for is_multiple unless specified
1421 !$customFields[$customFieldId]['is_multiple'] &&
1422 $entityId
1423 ) {
1424 $query = "
1425 SELECT id
1426 FROM $tableName
1427 WHERE entity_id={$entityId}";
1428
1429 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1430 }
1431
1432 //fix checkbox, now check box always submits values
1433 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1434 if ($value) {
1435 // Note that only during merge this is not an array, and you can directly use value
1436 if (is_array($value)) {
1437 $selectedValues = [];
1438 foreach ($value as $selId => $val) {
1439 if ($val) {
1440 $selectedValues[] = $selId;
1441 }
1442 }
1443 if (!empty($selectedValues)) {
1444 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1445 $selectedValues
1446 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1447 }
1448 else {
1449 $value = '';
1450 }
1451 }
1452 }
1453 }
1454 elseif (self::isSerialized($customFields[$customFieldId])) {
1455 $value = $value ? CRM_Utils_Array::implodePadded($value) : '';
1456 }
1457
1458 if (self::isSerialized($customFields[$customFieldId]) &&
1459 $customFields[$customFieldId]['data_type'] == 'String' &&
1460 !empty($customFields[$customFieldId]['text_length']) &&
1461 !empty($value)
1462 ) {
1463 // lets make sure that value is less than the length, else we'll
1464 // be losing some data, CRM-7481
1465 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1466 // need to do a few things here
1467
1468 // 1. lets find a new length
1469 $newLength = $customFields[$customFieldId]['text_length'];
1470 $minLength = strlen($value);
1471 while ($newLength < $minLength) {
1472 $newLength = $newLength * 2;
1473 }
1474
1475 // set the custom field meta data to have a length larger than value
1476 // alter the custom value table column to match this length
1477 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1478 }
1479 }
1480
1481 $date = NULL;
1482 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1483 if (!CRM_Utils_System::isNull($value)) {
1484 $format = $customFields[$customFieldId]['date_format'];
1485 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1486 }
1487 $value = $date;
1488 }
1489
1490 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1491 $customFields[$customFieldId]['data_type'] == 'Money'
1492 ) {
1493 if (!$value) {
1494 $value = 0;
1495 }
1496
1497 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1498 $value = CRM_Utils_Rule::cleanMoney($value);
1499 }
1500 }
1501
1502 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1503 $customFields[$customFieldId]['data_type'] == 'Country'
1504 ) &&
1505 empty($value)
1506 ) {
1507 // CRM-3415
1508 $value = 0;
1509 }
1510
1511 $fileID = NULL;
1512
1513 if ($customFields[$customFieldId]['data_type'] == 'File') {
1514 if (empty($value)) {
1515 return;
1516 }
1517
1518 $config = CRM_Core_Config::singleton();
1519
1520 // If we are already passing the file id as a value then retrieve and set the file data
1521 if (CRM_Utils_Rule::integer($value)) {
1522 $fileDAO = new CRM_Core_DAO_File();
1523 $fileDAO->id = $value;
1524 $fileDAO->find(TRUE);
1525 if ($fileDAO->N) {
1526 $fileID = $value;
1527 $fName = $fileDAO->uri;
1528 $mimeType = $fileDAO->mime_type;
1529 }
1530 }
1531 else {
1532 $fName = $value['name'];
1533 $mimeType = $value['type'];
1534 }
1535
1536 $filename = pathinfo($fName, PATHINFO_BASENAME);
1537
1538 // rename this file to go into the secure directory only if
1539 // user has uploaded new file not existing verfied on the basis of $fileID
1540 if (empty($fileID) && !rename($fName, $config->customFileUploadDir . $filename)) {
1541 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
1542 }
1543
1544 if ($customValueId && empty($fileID)) {
1545 $query = "
1546 SELECT $columnName
1547 FROM $tableName
1548 WHERE id = %1";
1549 $params = [1 => [$customValueId, 'Integer']];
1550 $fileID = CRM_Core_DAO::singleValueQuery($query, $params);
1551 }
1552
1553 $fileDAO = new CRM_Core_DAO_File();
1554
1555 if ($fileID) {
1556 $fileDAO->id = $fileID;
1557 }
1558
1559 $fileDAO->uri = $filename;
1560 $fileDAO->mime_type = $mimeType;
1561 $fileDAO->upload_date = date('YmdHis');
1562 $fileDAO->save();
1563 $fileID = $fileDAO->id;
1564 $value = $filename;
1565 }
1566
1567 if (!is_array($customFormatted)) {
1568 $customFormatted = [];
1569 }
1570
1571 if (!array_key_exists($customFieldId, $customFormatted)) {
1572 $customFormatted[$customFieldId] = [];
1573 }
1574
1575 $index = -1;
1576 if ($customValueId) {
1577 $index = $customValueId;
1578 }
1579
1580 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1581 $customFormatted[$customFieldId][$index] = [];
1582 }
1583 $customFormatted[$customFieldId][$index] = [
1584 'id' => $customValueId > 0 ? $customValueId : NULL,
1585 'value' => $value,
1586 'type' => $customFields[$customFieldId]['data_type'],
1587 'custom_field_id' => $customFieldId,
1588 'custom_group_id' => $groupID,
1589 'table_name' => $tableName,
1590 'column_name' => $columnName,
1591 'file_id' => $fileID,
1592 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1593 ];
1594
1595 //we need to sort so that custom fields are created in the order of entry
1596 krsort($customFormatted[$customFieldId]);
1597 return $customFormatted;
1598 }
1599
1600 /**
1601 * Get default custom table schema.
1602 *
1603 * @param array $params
1604 *
1605 * @return array
1606 */
1607 public static function defaultCustomTableSchema($params) {
1608 // add the id and extends_id
1609 $table = [
1610 'name' => $params['name'],
1611 'is_multiple' => $params['is_multiple'],
1612 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1613 'fields' => [
1614 [
1615 'name' => 'id',
1616 'type' => 'int unsigned',
1617 'primary' => TRUE,
1618 'required' => TRUE,
1619 'attributes' => 'AUTO_INCREMENT',
1620 'comment' => 'Default MySQL primary key',
1621 ],
1622 [
1623 'name' => 'entity_id',
1624 'type' => 'int unsigned',
1625 'required' => TRUE,
1626 'comment' => 'Table that this extends',
1627 'fk_table_name' => $params['extends_name'],
1628 'fk_field_name' => 'id',
1629 'fk_attributes' => 'ON DELETE CASCADE',
1630 ],
1631 ],
1632 ];
1633
1634 if (!$params['is_multiple']) {
1635 $table['indexes'] = [
1636 [
1637 'unique' => TRUE,
1638 'field_name_1' => 'entity_id',
1639 ],
1640 ];
1641 }
1642 return $table;
1643 }
1644
1645 /**
1646 * Create custom field.
1647 *
1648 * @param CRM_Core_DAO_CustomField $field
1649 * @param string $operation
1650 */
1651 public static function createField($field, $operation) {
1652 $sql = str_repeat(' ', 8);
1653 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id, 'table_name');
1654 $sql .= "ALTER TABLE " . $tableName;
1655 $sql .= self::getAlterFieldSQL($field, $operation);
1656
1657 // CRM-7007: do not i18n-rewrite this query
1658 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1659
1660 $config = CRM_Core_Config::singleton();
1661 if ($config->logging) {
1662 // CRM-16717 not sure why this was originally limited to add.
1663 // For example custom tables can have field length changes - which need to flow through to logging.
1664 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1665 if ($operation === 'add' || $operation === 'modify') {
1666 $logging = new CRM_Logging_Schema();
1667 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name]]);
1668 }
1669 }
1670
1671 Civi::service('sql_triggers')->rebuild($tableName, TRUE);
1672 }
1673
1674 /**
1675 * @param CRM_Core_DAO_CustomField $field
1676 * @param string $operation
1677 *
1678 * @return bool
1679 */
1680 public static function getAlterFieldSQL($field, $operation) {
1681 $indexExist = $operation === 'add' ? FALSE : CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $field->id, 'is_searchable');
1682 $params = self::prepareCreateParams($field, $operation);
1683 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1684 // a function only used by Custom Field creation...
1685 $params['required'] = FALSE;
1686 return CRM_Core_BAO_SchemaHandler::getFieldAlterSQL($params, $indexExist);
1687 }
1688
1689 /**
1690 * Determine whether it would be safe to move a field.
1691 *
1692 * @param int $fieldID
1693 * FK to civicrm_custom_field.
1694 * @param int $newGroupID
1695 * FK to civicrm_custom_group.
1696 *
1697 * @return array
1698 * array(string) or TRUE
1699 */
1700 public static function _moveFieldValidate($fieldID, $newGroupID) {
1701 $errors = [];
1702
1703 $field = new CRM_Core_DAO_CustomField();
1704 $field->id = $fieldID;
1705 if (!$field->find(TRUE)) {
1706 $errors['fieldID'] = 'Invalid ID for custom field';
1707 return $errors;
1708 }
1709
1710 $oldGroup = new CRM_Core_DAO_CustomGroup();
1711 $oldGroup->id = $field->custom_group_id;
1712 if (!$oldGroup->find(TRUE)) {
1713 $errors['fieldID'] = 'Invalid ID for old custom group';
1714 return $errors;
1715 }
1716
1717 $newGroup = new CRM_Core_DAO_CustomGroup();
1718 $newGroup->id = $newGroupID;
1719 if (!$newGroup->find(TRUE)) {
1720 $errors['newGroupID'] = 'Invalid ID for new custom group';
1721 return $errors;
1722 }
1723
1724 $query = "
1725 SELECT b.id
1726 FROM civicrm_custom_field a
1727 INNER JOIN civicrm_custom_field b
1728 WHERE a.id = %1
1729 AND a.label = b.label
1730 AND b.custom_group_id = %2
1731 ";
1732 $params = [
1733 1 => [$field->id, 'Integer'],
1734 2 => [$newGroup->id, 'Integer'],
1735 ];
1736 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1737 if ($count > 0) {
1738 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1739 }
1740
1741 $tableName = $oldGroup->table_name;
1742 $columnName = $field->column_name;
1743
1744 $query = "
1745 SELECT count(*)
1746 FROM $tableName
1747 WHERE $columnName is not null
1748 ";
1749 $count = CRM_Core_DAO::singleValueQuery($query);
1750 if ($count > 0) {
1751 $query = "
1752 SELECT extends
1753 FROM civicrm_custom_group
1754 WHERE id IN ( %1, %2 )
1755 ";
1756 $params = [
1757 1 => [$oldGroup->id, 'Integer'],
1758 2 => [$newGroup->id, 'Integer'],
1759 ];
1760
1761 $dao = CRM_Core_DAO::executeQuery($query, $params);
1762 $extends = [];
1763 while ($dao->fetch()) {
1764 $extends[] = $dao->extends;
1765 }
1766 if ($extends[0] != $extends[1]) {
1767 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1768 }
1769 }
1770
1771 return empty($errors) ? TRUE : $errors;
1772 }
1773
1774 /**
1775 * Move a custom data field from one group (table) to another.
1776 *
1777 * @param int $fieldID
1778 * FK to civicrm_custom_field.
1779 * @param int $newGroupID
1780 * FK to civicrm_custom_group.
1781 *
1782 * @throws CRM_Core_Exception
1783 */
1784 public static function moveField($fieldID, $newGroupID) {
1785 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
1786 if (TRUE !== $validation) {
1787 throw new CRM_Core_Exception(implode(' ', $validation));
1788 }
1789 $field = new CRM_Core_DAO_CustomField();
1790 $field->id = $fieldID;
1791 $field->find(TRUE);
1792
1793 $newGroup = new CRM_Core_DAO_CustomGroup();
1794 $newGroup->id = $newGroupID;
1795 $newGroup->find(TRUE);
1796
1797 $oldGroup = new CRM_Core_DAO_CustomGroup();
1798 $oldGroup->id = $field->custom_group_id;
1799 $oldGroup->find(TRUE);
1800
1801 $add = clone$field;
1802 $add->custom_group_id = $newGroup->id;
1803 self::createField($add, 'add');
1804
1805 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1806 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1807 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1808 ";
1809 CRM_Core_DAO::executeQuery($sql);
1810
1811 $del = clone$field;
1812 $del->custom_group_id = $oldGroup->id;
1813 self::createField($del, 'delete');
1814
1815 $add->save();
1816
1817 CRM_Utils_System::flushCache();
1818 }
1819
1820 /**
1821 * Create an option value for a custom field option group ID.
1822 *
1823 * @param array $params
1824 * @param string $value
1825 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1826 * @param string $index
1827 * @param string $dataType
1828 */
1829 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup $optionGroup, $index, $dataType) {
1830 if (strlen(trim($value))) {
1831 $optionValue = new CRM_Core_DAO_OptionValue();
1832 $optionValue->option_group_id = $optionGroup->id;
1833 $optionValue->label = $params['option_label'][$index];
1834 $optionValue->name = $params['option_name'][$index] ?? CRM_Utils_String::titleToVar($params['option_label'][$index]);
1835 switch ($dataType) {
1836 case 'Money':
1837 $optionValue->value = CRM_Utils_Rule::cleanMoney($value);
1838 break;
1839
1840 case 'Int':
1841 $optionValue->value = intval($value);
1842 break;
1843
1844 case 'Float':
1845 $optionValue->value = floatval($value);
1846 break;
1847
1848 default:
1849 $optionValue->value = trim($value);
1850 }
1851
1852 $optionValue->weight = $params['option_weight'][$index];
1853 $optionValue->is_active = $params['option_status'][$index] ?? FALSE;
1854 $optionValue->description = $params['option_description'][$index] ?? NULL;
1855 $optionValue->color = $params['option_color'][$index] ?? NULL;
1856 $optionValue->icon = $params['option_icon'][$index] ?? NULL;
1857 $optionValue->save();
1858 }
1859 }
1860
1861 /**
1862 * Prepare for the create operation.
1863 *
1864 * Munge params, create the option values if needed.
1865 *
1866 * This could be called by a single create or a batchCreate.
1867 *
1868 * @param array $params
1869 *
1870 * @return array
1871 */
1872 protected static function prepareCreate($params) {
1873 $op = empty($params['id']) ? 'create' : 'edit';
1874 CRM_Utils_Hook::pre($op, 'CustomField', CRM_Utils_Array::value('id', $params), $params);
1875 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1876 if ($op === 'create') {
1877 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
1878 if (!isset($params['column_name'])) {
1879 // if add mode & column_name not present, calculate it.
1880 $params['column_name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 32));
1881 }
1882 if (!isset($params['name'])) {
1883 $params['name'] = CRM_Utils_String::munge($params['label'], '_', 64);
1884 }
1885 }
1886 else {
1887 $params['column_name'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1888 }
1889
1890 $htmlType = $params['html_type'] ?? NULL;
1891 $dataType = $params['data_type'] ?? NULL;
1892
1893 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1894 $params['date_format'] = Civi::settings()->get('dateInputFormat');
1895 }
1896
1897 // Checkboxes are always serialized in current schema
1898 if ($htmlType == 'CheckBox') {
1899 $params['serialize'] = CRM_Core_DAO::SERIALIZE_SEPARATOR_BOOKEND;
1900 }
1901
1902 if (!empty($params['serialize'])) {
1903 if (isset($params['default_checkbox_option'])) {
1904 $defaultArray = [];
1905 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1906 if ($params['option_value'][$v]) {
1907 $defaultArray[] = $params['option_value'][$v];
1908 }
1909 }
1910
1911 if (!empty($defaultArray)) {
1912 // also add the separator before and after the value per new convention (CRM-1604)
1913 $params['default_value'] = CRM_Utils_Array::implodePadded($defaultArray);
1914 }
1915 }
1916 else {
1917 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1918 $params['default_value'] = $params['option_value'][$params['default_option']];
1919 }
1920 }
1921 }
1922
1923 // create any option group & values if required
1924 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1925 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
1926 //CRM-16659: if option_value then create an option group for this custom field.
1927 if ($params['option_type'] == 1 && (empty($params['option_group_id']) || !empty($params['option_value']))) {
1928 // first create an option group for this custom group
1929 $optionGroup = new CRM_Core_DAO_OptionGroup();
1930 $optionGroup->name = "{$params['column_name']}_" . date('YmdHis');
1931 $optionGroup->title = $params['label'];
1932 $optionGroup->is_active = 1;
1933 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1934 $optionGroup->is_reserved = 0;
1935 $optionGroup->data_type = $dataType;
1936 $optionGroup->save();
1937 $params['option_group_id'] = $optionGroup->id;
1938 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1939 foreach ($params['option_value'] as $k => $v) {
1940 self::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1941 }
1942 }
1943 }
1944 }
1945
1946 // check for orphan option groups
1947 if (!empty($params['option_group_id'])) {
1948 if (!empty($params['id'])) {
1949 self::fixOptionGroups($params['id'], $params['option_group_id']);
1950 }
1951
1952 // if we do not have a default value
1953 // retrieve it from one of the other custom fields which use this option group
1954 if (empty($params['default_value'])) {
1955 //don't insert only value separator as default value, CRM-4579
1956 $defaultValue = self::getOptionGroupDefault($params['option_group_id'], !empty($params['serialize']));
1957
1958 if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaultValue))) {
1959 $params['default_value'] = $defaultValue;
1960 }
1961 }
1962 }
1963
1964 // Set default textarea attributes
1965 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
1966 $params['attributes'] = 'rows=4, cols=60';
1967 }
1968 return $params;
1969 }
1970
1971 /**
1972 * Create database entry for custom field and related option groups.
1973 *
1974 * @param array $params
1975 *
1976 * @return CRM_Core_DAO_CustomField
1977 */
1978 protected static function createCustomFieldRecord($params) {
1979 $transaction = new CRM_Core_Transaction();
1980 $params = self::prepareCreate($params);
1981
1982 $customField = new CRM_Core_DAO_CustomField();
1983 $customField->copyValues($params);
1984 $customField->save();
1985
1986 //create/drop the index when we toggle the is_searchable flag
1987 $op = empty($params['id']) ? 'add' : 'modify';
1988 if ($op !== 'modify') {
1989 if ($params['is_append_field_id_to_column_name']) {
1990 $params['column_name'] .= "_{$customField->id}";
1991 }
1992 $customField->column_name = $params['column_name'];
1993 $customField->save();
1994 }
1995
1996 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
1997 $transaction->commit();
1998
1999 // make sure all values are present in the object for further processing
2000 $customField->find(TRUE);
2001 return $customField;
2002 }
2003
2004 /**
2005 * Move custom data from one contact to another.
2006 *
2007 * This is currently the start of a refactoring. The theory is each
2008 * entity could have a 'move' function with a DAO default one to fall back on.
2009 *
2010 * At the moment this only does a small part of the process - ie deleting a file field that
2011 * is about to be overwritten. However, the goal is the whole process around the move for
2012 * custom data should be in here.
2013 *
2014 * This is currently called by the merge class but it makes sense that api could
2015 * expose move actions as moving (e.g) contributions feels like a common
2016 * ask that should be handled by the form layer.
2017 *
2018 * @param int $oldContactID
2019 * @param int $newContactID
2020 * @param int[] $fieldIDs
2021 * Optional list field ids to move.
2022 *
2023 * @throws \CiviCRM_API3_Exception
2024 * @throws \Exception
2025 */
2026 public function move($oldContactID, $newContactID, $fieldIDs) {
2027 if (empty($fieldIDs)) {
2028 return;
2029 }
2030 $fields = civicrm_api3('CustomField', 'get', ['id' => ['IN' => $fieldIDs], 'return' => ['custom_group_id.is_multiple', 'custom_group_id.table_name', 'column_name', 'data_type'], 'options' => ['limit' => 0]])['values'];
2031 $return = [];
2032 foreach ($fieldIDs as $fieldID) {
2033 $return[] = 'custom_' . $fieldID;
2034 }
2035 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2036 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2037
2038 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2039 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2040 $fieldTypesNotHandledInMergeAttempt = ['File'];
2041 foreach ($fields as $field) {
2042 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2043 if ($field['data_type'] === 'File' && !$isMultiple) {
2044 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2045 CRM_Core_BAO_File::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2046 }
2047 if (!empty($oldContact['custom_' . $field['id']])) {
2048 CRM_Core_DAO::executeQuery("
2049 UPDATE civicrm_entity_file
2050 SET entity_id = $newContactID
2051 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2052 );
2053 }
2054 }
2055 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2056 CRM_Core_DAO::executeQuery(
2057 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2058 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2059 ON DUPLICATE KEY UPDATE
2060 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2061 ");
2062 }
2063 }
2064 }
2065
2066 /**
2067 * Get the database table name and column name for a custom field.
2068 *
2069 * @param int $fieldID
2070 * The fieldID of the custom field.
2071 * @param bool $force
2072 * Force the sql to be run again (primarily used for tests).
2073 *
2074 * @return array
2075 * fatal is fieldID does not exists, else array of tableName, columnName
2076 * @throws \CRM_Core_Exception
2077 */
2078 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2079 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2080 $cache = CRM_Utils_Cache::singleton();
2081 $fieldValues = $cache->get($cacheKey);
2082 if (empty($fieldValues) || $force) {
2083 $query = "
2084 SELECT cg.table_name, cf.column_name, cg.id
2085 FROM civicrm_custom_group cg,
2086 civicrm_custom_field cf
2087 WHERE cf.custom_group_id = cg.id
2088 AND cf.id = %1";
2089 $params = [1 => [$fieldID, 'Integer']];
2090 $dao = CRM_Core_DAO::executeQuery($query, $params);
2091
2092 if (!$dao->fetch()) {
2093 throw new CRM_Core_Exception("Cannot find table and column information for Custom Field " . $fieldID);
2094 }
2095 $fieldValues = [$dao->table_name, $dao->column_name, $dao->id];
2096 $cache->set($cacheKey, $fieldValues);
2097 }
2098 return $fieldValues;
2099 }
2100
2101 /**
2102 * Get custom option groups.
2103 *
2104 * @deprecated Use the API OptionGroup.get
2105 *
2106 * @param array $includeFieldIds
2107 * Ids of custom fields for which option groups must be included.
2108 *
2109 * Currently this is required in the cases where option groups are to be included
2110 * for inactive fields : CRM-5369
2111 *
2112 * @return mixed
2113 */
2114 public static function customOptionGroup($includeFieldIds = NULL) {
2115 static $customOptionGroup = NULL;
2116
2117 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
2118 if ($cacheKey == 'force') {
2119 $customOptionGroup[$cacheKey] = NULL;
2120 }
2121
2122 if (empty($customOptionGroup[$cacheKey])) {
2123 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2124
2125 //support for single as well as array format.
2126 if (!empty($includeFieldIds)) {
2127 if (is_array($includeFieldIds)) {
2128 $includeFieldIds = implode(',', $includeFieldIds);
2129 }
2130 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2131 }
2132
2133 $query = "
2134 SELECT g.id, g.title
2135 FROM civicrm_option_group g
2136 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2137 WHERE {$whereClause}";
2138
2139 $dao = CRM_Core_DAO::executeQuery($query);
2140 while ($dao->fetch()) {
2141 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
2142 }
2143 }
2144
2145 return $customOptionGroup[$cacheKey];
2146 }
2147
2148 /**
2149 * Get defaults for new entity.
2150 *
2151 * @return array
2152 */
2153 public static function getDefaults() {
2154 return [
2155 'is_required' => FALSE,
2156 'is_searchable' => FALSE,
2157 'in_selector' => FALSE,
2158 'is_search_range' => FALSE,
2159 //CRM-15792 - Custom field gets disabled if is_active not set
2160 // this would ideally be a mysql default.
2161 'is_active' => TRUE,
2162 'is_view' => FALSE,
2163 ];
2164 }
2165
2166 /**
2167 * Fix orphan groups.
2168 *
2169 * @param int $customFieldId
2170 * Custom field id.
2171 * @param int $optionGroupId
2172 * Option group id.
2173 */
2174 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2175 // check if option group belongs to any custom Field else delete
2176 // get the current option group
2177 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2178 $customFieldId,
2179 'option_group_id'
2180 );
2181 // get the updated option group
2182 // if both are same return
2183 if (!$currentOptionGroupId || $currentOptionGroupId == $optionGroupId) {
2184 return;
2185 }
2186
2187 // check if option group is related to any other field
2188 self::checkOptionGroup($currentOptionGroupId);
2189 }
2190
2191 /**
2192 * Check if option group is related to more than one custom field.
2193 *
2194 * @param int $optionGroupId
2195 * Option group id.
2196 */
2197 public static function checkOptionGroup($optionGroupId) {
2198 $query = "
2199 SELECT count(*)
2200 FROM civicrm_custom_field
2201 WHERE option_group_id = {$optionGroupId}";
2202
2203 $count = CRM_Core_DAO::singleValueQuery($query);
2204
2205 if ($count < 2) {
2206 //delete the option group
2207 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2208 }
2209 }
2210
2211 /**
2212 * Get option group default.
2213 *
2214 * @param int $optionGroupId
2215 * @param bool $serialize
2216 *
2217 * @return null|string
2218 */
2219 public static function getOptionGroupDefault($optionGroupId, $serialize) {
2220 $query = "
2221 SELECT default_value, serialize
2222 FROM civicrm_custom_field
2223 WHERE option_group_id = {$optionGroupId}
2224 AND default_value IS NOT NULL";
2225
2226 $dao = CRM_Core_DAO::executeQuery($query);
2227 while ($dao->fetch()) {
2228 if ($dao->serialize == $serialize) {
2229 return $dao->default_value;
2230 }
2231 $defaultValue = $dao->default_value;
2232 }
2233
2234 // Convert serialization
2235 if (isset($defaultValue) && $serialize) {
2236 return CRM_Utils_Array::implodePadded([$defaultValue]);
2237 }
2238 elseif (isset($defaultValue)) {
2239 return CRM_Utils_Array::explodePadded($defaultValue)[0];
2240 }
2241 return NULL;
2242 }
2243
2244 /**
2245 * Post process function.
2246 *
2247 * @param array $params
2248 * @param int $entityID
2249 * @param string $customFieldExtends
2250 * @param bool $inline
2251 * @param bool $checkPermissions
2252 *
2253 * @return array
2254 */
2255 public static function postProcess(
2256 &$params,
2257 $entityID,
2258 $customFieldExtends,
2259 $inline = FALSE,
2260 $checkPermissions = TRUE
2261 ) {
2262 $customData = [];
2263
2264 foreach ($params as $key => $value) {
2265 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE)) {
2266
2267 // for autocomplete transfer hidden value instead of label
2268 if ($params[$key] && isset($params[$key . '_id'])) {
2269 $value = $params[$key . '_id'];
2270 }
2271
2272 // we need to append time with date
2273 if ($params[$key] && isset($params[$key . '_time'])) {
2274 $value .= ' ' . $params[$key . '_time'];
2275 }
2276
2277 CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0],
2278 $customData,
2279 $value,
2280 $customFieldExtends,
2281 $customFieldInfo[1],
2282 $entityID,
2283 $inline,
2284 $checkPermissions
2285 );
2286 }
2287 }
2288 return $customData;
2289 }
2290
2291 /**
2292 * Get custom field ID from field/group name/title.
2293 *
2294 * @param string $fieldName Field name or label
2295 * @param string|null $groupName (Optional) Group name or label
2296 * @param bool $fullString Whether to return "custom_123" or "123"
2297 *
2298 * @return string|int|null
2299 * @throws \CiviCRM_API3_Exception
2300 */
2301 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2302 $cacheKey = $groupName . '.' . $fieldName;
2303 if (!isset(Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2304 $customFieldParams = [
2305 'name' => $fieldName,
2306 'label' => $fieldName,
2307 'options' => ['or' => [["name", "label"]]],
2308 ];
2309
2310 if ($groupName) {
2311 $customFieldParams['custom_group_id.name'] = $groupName;
2312 $customFieldParams['custom_group_id.title'] = $groupName;
2313 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2314 }
2315
2316 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2317
2318 if (empty($field['id'])) {
2319 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2320 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2321 }
2322 else {
2323 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2324 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2325 }
2326 }
2327
2328 if ($fullString) {
2329 return Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2330 }
2331 return Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2332 }
2333
2334 /**
2335 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2336 *
2337 * @param array $ids
2338 *
2339 * @return array
2340 */
2341 public static function getNameFromID($ids) {
2342 if (is_array($ids)) {
2343 $ids = implode(',', $ids);
2344 }
2345 $sql = "
2346 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2347 FROM civicrm_custom_field f
2348 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2349 WHERE f.id IN ($ids)";
2350
2351 $dao = CRM_Core_DAO::executeQuery($sql);
2352 $result = [];
2353 while ($dao->fetch()) {
2354 $result[$dao->id] = [
2355 'field_name' => $dao->field_name,
2356 'field_label' => $dao->field_label,
2357 'group_name' => $dao->group_name,
2358 'group_title' => $dao->group_title,
2359 ];
2360 }
2361 return $result;
2362 }
2363
2364 /**
2365 * Validate custom data.
2366 *
2367 * @param array $params
2368 * Custom data submitted.
2369 * ie array( 'custom_1' => 'validate me' );
2370 *
2371 * @return array
2372 * validation errors.
2373 */
2374 public static function validateCustomData($params) {
2375 $errors = [];
2376 if (!is_array($params) || empty($params)) {
2377 return $errors;
2378 }
2379
2380 //pick up profile fields.
2381 $profileFields = [];
2382 $ufGroupId = $params['ufGroupId'] ?? NULL;
2383 if ($ufGroupId) {
2384 $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId,
2385 FALSE,
2386 CRM_Core_Action::VIEW
2387 );
2388 }
2389
2390 //lets start w/ params.
2391 foreach ($params as $key => $value) {
2392 $customFieldID = self::getKeyID($key);
2393 if (!$customFieldID) {
2394 continue;
2395 }
2396
2397 //load the structural info for given field.
2398 $field = new CRM_Core_DAO_CustomField();
2399 $field->id = $customFieldID;
2400 if (!$field->find(TRUE)) {
2401 continue;
2402 }
2403 $dataType = $field->data_type;
2404
2405 $profileField = CRM_Utils_Array::value($key, $profileFields, []);
2406 $fieldTitle = $profileField['title'] ?? NULL;
2407 $isRequired = $profileField['is_required'] ?? NULL;
2408 if (!$fieldTitle) {
2409 $fieldTitle = $field->label;
2410 }
2411
2412 //no need to validate.
2413 if (CRM_Utils_System::isNull($value) && !$isRequired) {
2414 continue;
2415 }
2416
2417 //lets validate first for required field.
2418 if ($isRequired && CRM_Utils_System::isNull($value)) {
2419 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2420 continue;
2421 }
2422
2423 //now time to take care of custom field form rules.
2424 $ruleName = $errorMsg = NULL;
2425 switch ($dataType) {
2426 case 'Int':
2427 $ruleName = 'integer';
2428 $errorMsg = ts('%1 must be an integer (whole number).',
2429 array(1 => $fieldTitle)
2430 );
2431 break;
2432
2433 case 'Money':
2434 $ruleName = 'money';
2435 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2436 array(1 => $fieldTitle)
2437 );
2438 break;
2439
2440 case 'Float':
2441 $ruleName = 'numeric';
2442 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2443 array(1 => $fieldTitle)
2444 );
2445 break;
2446
2447 case 'Link':
2448 $ruleName = 'wikiURL';
2449 $errorMsg = ts('%1 must be valid Website.',
2450 array(1 => $fieldTitle)
2451 );
2452 break;
2453 }
2454
2455 if ($ruleName && !CRM_Utils_System::isNull($value)) {
2456 $valid = FALSE;
2457 $funName = "CRM_Utils_Rule::{$ruleName}";
2458 if (is_callable($funName)) {
2459 $valid = call_user_func($funName, $value);
2460 }
2461 if (!$valid) {
2462 $errors[$key] = $errorMsg;
2463 }
2464 }
2465 }
2466
2467 return $errors;
2468 }
2469
2470 /**
2471 * Is this field a multi record field.
2472 *
2473 * @param int $customId
2474 *
2475 * @return bool
2476 */
2477 public static function isMultiRecordField($customId) {
2478 $isMultipleWithGid = FALSE;
2479 if (!is_numeric($customId)) {
2480 $customId = self::getKeyID($customId);
2481 }
2482 if (is_numeric($customId)) {
2483 $sql = "SELECT cg.id cgId
2484 FROM civicrm_custom_group cg
2485 INNER JOIN civicrm_custom_field cf
2486 ON cg.id = cf.custom_group_id
2487 WHERE cf.id = %1 AND cg.is_multiple = 1";
2488 $params[1] = [$customId, 'Integer'];
2489 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2490 if ($dao->fetch()) {
2491 if ($dao->cgId) {
2492 $isMultipleWithGid = $dao->cgId;
2493 }
2494 }
2495 }
2496
2497 return $isMultipleWithGid;
2498 }
2499
2500 /**
2501 * Does this field type have any select options?
2502 *
2503 * @param array $field
2504 *
2505 * @return bool
2506 */
2507 public static function hasOptions($field) {
2508 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2509 $field = (array) $field;
2510 // This will include boolean fields with Yes/No options.
2511 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2512 return TRUE;
2513 }
2514 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2515 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2516 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2517 return FALSE;
2518 }
2519 if (strpos($field['html_type'], 'Select') !== FALSE) {
2520 return TRUE;
2521 }
2522 return !empty($field['option_group_id']);
2523 }
2524
2525 /**
2526 * Does this field store a serialized string?
2527 *
2528 * @param CRM_Core_DAO_CustomField|array $field
2529 *
2530 * @return bool
2531 */
2532 public static function isSerialized($field) {
2533 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2534 $html_type = is_object($field) ? $field->html_type : $field['html_type'];
2535 // APIv3 has a "legacy" mode where it returns old-style html_type of "Multi-Select"
2536 // If anyone is using this function in conjunction with legacy api output, we'll accomodate:
2537 if ($html_type === 'CheckBox' || strpos($html_type, 'Multi') !== FALSE) {
2538 return TRUE;
2539 }
2540 // Otherwise this is the new standard as of 5.26
2541 return is_object($field) ? !empty($field->serialize) : !empty($field['serialize']);
2542 }
2543
2544 /**
2545 * Get api entity for this field
2546 *
2547 * @return string
2548 */
2549 public function getEntity() {
2550 $entity = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id, 'extends');
2551 return in_array($entity, ['Individual', 'Household', 'Organization']) ? 'Contact' : $entity;
2552 }
2553
2554 /**
2555 * Set pseudoconstant properties for field metadata.
2556 *
2557 * @param array $field
2558 * @param string|null $optionGroupName
2559 */
2560 private static function getOptionsForField(&$field, $optionGroupName) {
2561 if ($optionGroupName) {
2562 $field['pseudoconstant'] = [
2563 'optionGroupName' => $optionGroupName,
2564 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2565 ];
2566 }
2567 elseif ($field['data_type'] == 'Boolean') {
2568 $field['pseudoconstant'] = [
2569 'callback' => 'CRM_Core_SelectValues::boolean',
2570 ];
2571 }
2572 elseif ($field['data_type'] == 'Country') {
2573 $field['pseudoconstant'] = [
2574 'table' => 'civicrm_country',
2575 'keyColumn' => 'id',
2576 'labelColumn' => 'name',
2577 'nameColumn' => 'iso_code',
2578 ];
2579 }
2580 elseif ($field['data_type'] == 'StateProvince') {
2581 $field['pseudoconstant'] = [
2582 'table' => 'civicrm_state_province',
2583 'keyColumn' => 'id',
2584 'labelColumn' => 'name',
2585 ];
2586 }
2587 }
2588
2589 /**
2590 * @param CRM_Core_DAO_CustomField $field
2591 * @param 'add|modify' $operation
2592 *
2593 * @return array
2594 */
2595 protected static function prepareCreateParams($field, $operation) {
2596 $tableName = CRM_Core_DAO::getFieldValue(
2597 'CRM_Core_DAO_CustomGroup',
2598 $field->custom_group_id,
2599 'table_name'
2600 );
2601
2602 $params = [
2603 'table_name' => $tableName,
2604 'operation' => $operation,
2605 'name' => $field->column_name,
2606 'type' => CRM_Core_BAO_CustomValueTable::fieldToSQLType(
2607 $field->data_type,
2608 $field->text_length
2609 ),
2610 'required' => $field->is_required,
2611 'searchable' => $field->is_searchable,
2612 ];
2613
2614 if ($operation == 'delete') {
2615 $fkName = "{$tableName}_{$field->column_name}";
2616 if (strlen($fkName) >= 48) {
2617 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2618 }
2619 $params['fkName'] = $fkName;
2620 }
2621 if ($field->data_type == 'Country' && !self::isSerialized($field)) {
2622 $params['fk_table_name'] = 'civicrm_country';
2623 $params['fk_field_name'] = 'id';
2624 $params['fk_attributes'] = 'ON DELETE SET NULL';
2625 }
2626 elseif ($field->data_type == 'StateProvince' && !self::isSerialized($field)) {
2627 $params['fk_table_name'] = 'civicrm_state_province';
2628 $params['fk_field_name'] = 'id';
2629 $params['fk_attributes'] = 'ON DELETE SET NULL';
2630 }
2631 elseif ($field->data_type == 'StateProvince' || $field->data_type == 'Country') {
2632 $params['type'] = 'varchar(255)';
2633 }
2634 elseif ($field->data_type == 'File') {
2635 $params['fk_table_name'] = 'civicrm_file';
2636 $params['fk_field_name'] = 'id';
2637 $params['fk_attributes'] = 'ON DELETE SET NULL';
2638 }
2639 elseif ($field->data_type == 'ContactReference') {
2640 $params['fk_table_name'] = 'civicrm_contact';
2641 $params['fk_field_name'] = 'id';
2642 $params['fk_attributes'] = 'ON DELETE SET NULL';
2643 }
2644 if (isset($field->default_value)) {
2645 $params['default'] = "'{$field->default_value}'";
2646 }
2647 return $params;
2648 }
2649
2650 }