Rely on serialize property when checking if custom field is multivalued
[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 * Store and return an array of all active custom fields.
247 *
248 * @param string $customDataType
249 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
250 * @param bool $showAll
251 * If true returns all fields (includes disabled fields).
252 * @param bool $inline
253 * If true returns all inline fields (includes disabled fields).
254 * @param int $customDataSubType
255 * Custom Data sub type value.
256 * @param int $customDataSubName
257 * Custom Data sub name value.
258 * @param bool $onlyParent
259 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
260 * @param bool $onlySubType
261 * Return only custom data for subtype.
262 * @param bool $checkPermission
263 * If false, do not include permissioning clause.
264 *
265 * @return array
266 * an array of active custom fields.
267 */
268 public static function &getFields(
269 $customDataType = 'Individual',
270 $showAll = FALSE,
271 $inline = FALSE,
272 $customDataSubType = NULL,
273 $customDataSubName = NULL,
274 $onlyParent = FALSE,
275 $onlySubType = FALSE,
276 $checkPermission = TRUE
277 ) {
278 if (empty($customDataType)) {
279 $customDataType = ['Contact', 'Individual', 'Organization', 'Household'];
280 }
281 if ($customDataType === 'ANY') {
282 // NULL should have been respected but the line above broke that.
283 // boo for us not having enough unit tests back them.
284 $customDataType = NULL;
285 }
286 if ($customDataType && !is_array($customDataType)) {
287
288 if (in_array($customDataType, CRM_Contact_BAO_ContactType::subTypes())) {
289 // This is the case when getFieldsForImport() requires fields
290 // limited strictly to a subtype.
291 $customDataSubType = $customDataType;
292 $customDataType = CRM_Contact_BAO_ContactType::getBasicType($customDataType);
293 $onlySubType = TRUE;
294 }
295
296 if (in_array($customDataType, array_keys(CRM_Core_SelectValues::customGroupExtends()))) {
297 // this makes the method flexible to support retrieving fields
298 // for multiple extends value.
299 $customDataType = [$customDataType];
300 }
301 }
302
303 $customDataSubType = CRM_Utils_Array::explodePadded($customDataSubType);
304
305 if (is_array($customDataType)) {
306 $cacheKey = implode('_', $customDataType);
307 }
308 else {
309 $cacheKey = $customDataType;
310 }
311
312 $cacheKey .= !empty($customDataSubType) ? ('_' . implode('_', $customDataSubType)) : '_0';
313 $cacheKey .= $customDataSubName ? "{$customDataSubName}_" : '_0';
314 $cacheKey .= $showAll ? '_1' : '_0';
315 $cacheKey .= $inline ? '_1_' : '_0_';
316 $cacheKey .= $onlyParent ? '_1_' : '_0_';
317 $cacheKey .= $onlySubType ? '_1_' : '_0_';
318 $cacheKey .= $checkPermission ? '_1_' : '_0_';
319 $cacheKey .= '_' . CRM_Core_Config::domainID() . '_';
320
321 $cgTable = CRM_Core_DAO_CustomGroup::getTableName();
322
323 // also get the permission stuff here
324 if ($checkPermission) {
325 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
326 "{$cgTable}."
327 );
328 }
329 else {
330 $permissionClause = '(1)';
331 }
332
333 // lets md5 permission clause and take first 8 characters
334 $cacheKey .= substr(md5($permissionClause), 0, 8);
335
336 if (strlen($cacheKey) > 40) {
337 $cacheKey = md5($cacheKey);
338 }
339
340 if (!self::$_importFields ||
341 CRM_Utils_Array::value($cacheKey, self::$_importFields) === NULL
342 ) {
343 if (!self::$_importFields) {
344 self::$_importFields = [];
345 }
346
347 // check if we can retrieve from database cache
348 $fields = Civi::Cache('fields')->get("custom importableFields $cacheKey");
349
350 if ($fields === NULL) {
351 $cfTable = self::getTableName();
352
353 $extends = '';
354 if (is_array($customDataType)) {
355 $value = NULL;
356 foreach ($customDataType as $dataType) {
357 if (in_array($dataType, array_keys(CRM_Core_SelectValues::customGroupExtends()))) {
358 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
359 $val = "'" . CRM_Utils_Type::escape($dataType, 'String') . "', 'Contact' ";
360 }
361 else {
362 $val = "'" . CRM_Utils_Type::escape($dataType, 'String') . "'";
363 }
364 $value = $value ? $value . ", {$val}" : $val;
365 }
366 }
367 if ($value) {
368 $extends = "AND $cgTable.extends IN ( $value ) ";
369 }
370 }
371
372 if (!empty($customDataType) && empty($extends)) {
373 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
374 self::$_importFields[$cacheKey] = [];
375 return self::$_importFields[$cacheKey];
376 }
377
378 if ($onlyParent) {
379 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
380 }
381
382 $query = "SELECT $cfTable.id, $cfTable.label,
383 $cgTable.title,
384 $cfTable.data_type,
385 $cfTable.html_type,
386 $cfTable.default_value,
387 $cfTable.options_per_line, $cfTable.text_length,
388 $cfTable.custom_group_id,
389 $cfTable.is_required,
390 $cfTable.column_name,
391 $cgTable.extends, $cfTable.is_search_range,
392 $cgTable.extends_entity_column_value,
393 $cgTable.extends_entity_column_id,
394 $cfTable.is_view,
395 $cfTable.option_group_id,
396 $cfTable.date_format,
397 $cfTable.time_format,
398 $cgTable.is_multiple,
399 $cfTable.serialize,
400 $cgTable.table_name,
401 og.name as option_group_name
402 FROM $cfTable
403 INNER JOIN $cgTable
404 ON $cfTable.custom_group_id = $cgTable.id
405 LEFT JOIN civicrm_option_group og
406 ON $cfTable.option_group_id = og.id
407 WHERE ( 1 ) ";
408
409 if (!$showAll) {
410 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
411 }
412
413 if ($inline) {
414 $query .= " AND $cgTable.style = 'Inline' ";
415 }
416
417 //get the custom fields for specific type in
418 //combination with fields those support any type.
419 if (!empty($customDataSubType)) {
420 $subtypeClause = [];
421 foreach ($customDataSubType as $subtype) {
422 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($subtype, 'String') . CRM_Core_DAO::VALUE_SEPARATOR;
423 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
424 }
425 if (!$onlySubType) {
426 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
427 }
428 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
429 }
430
431 if ($customDataSubName) {
432 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
433 }
434
435 // also get the permission stuff here
436 if ($checkPermission) {
437 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
438 "{$cgTable}.", TRUE
439 );
440 }
441 else {
442 $permissionClause = '(1)';
443 }
444
445 $query .= " $extends AND $permissionClause
446 ORDER BY $cgTable.weight, $cgTable.title,
447 $cfTable.weight, $cfTable.label";
448
449 $dao = CRM_Core_DAO::executeQuery($query);
450
451 $fields = [];
452 while (($dao->fetch()) != NULL) {
453 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
454 $fields[$dao->id]['id'] = $dao->id;
455 $fields[$dao->id]['label'] = $dao->label;
456 // This seems broken, but not in a new way.
457 $fields[$dao->id]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
458 // To support the consolidation of various functions & their expectations.
459 $fields[$dao->id]['title'] = $dao->label;
460 $fields[$dao->id]['custom_field_id'] = $dao->id;
461 $fields[$dao->id]['groupTitle'] = $dao->title;
462 $fields[$dao->id]['data_type'] = $dao->data_type;
463 $fields[$dao->id]['name'] = 'custom_' . $dao->id;
464 $fields[$dao->id]['type'] = CRM_Utils_Array::value($dao->data_type, self::dataToType());
465 $fields[$dao->id]['html_type'] = $dao->html_type;
466 $fields[$dao->id]['default_value'] = $dao->default_value;
467 $fields[$dao->id]['text_length'] = $dao->text_length;
468 $fields[$dao->id]['options_per_line'] = $dao->options_per_line;
469 $fields[$dao->id]['custom_group_id'] = $dao->custom_group_id;
470 $fields[$dao->id]['extends'] = $dao->extends;
471 $fields[$dao->id]['is_search_range'] = $dao->is_search_range;
472 $fields[$dao->id]['extends_entity_column_value'] = $dao->extends_entity_column_value;
473 $fields[$dao->id]['extends_entity_column_id'] = $dao->extends_entity_column_id;
474 $fields[$dao->id]['is_view'] = $dao->is_view;
475 $fields[$dao->id]['is_multiple'] = $dao->is_multiple;
476 $fields[$dao->id]['option_group_id'] = $dao->option_group_id;
477 $fields[$dao->id]['date_format'] = $dao->date_format;
478 $fields[$dao->id]['time_format'] = $dao->time_format;
479 $fields[$dao->id]['is_required'] = $dao->is_required;
480 $fields[$dao->id]['table_name'] = $dao->table_name;
481 $fields[$dao->id]['column_name'] = $dao->column_name;
482 $fields[$dao->id]['serialize'] = $dao->serialize;
483 $fields[$dao->id]['where'] = $dao->table_name . '.' . $dao->column_name;
484 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
485 $fields[$dao->id]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery::$extendsMap) ? CRM_Core_BAO_CustomQuery::$extendsMap[$dao->extends] : '';
486 if (in_array($dao->extends, CRM_Contact_BAO_ContactType::subTypes())) {
487 // if $extends is a subtype, refer contact table
488 $fields[$dao->id]['extends_table'] = 'civicrm_contact';
489 }
490 // Search table is used by query object searches..
491 $fields[$dao->id]['search_table'] = ($fields[$dao->id]['extends_table'] == 'civicrm_contact') ? 'contact_a' : $fields[$dao->id]['extends_table'];
492 self::getOptionsForField($fields[$dao->id], $dao->option_group_name);
493 }
494
495 Civi::cache('fields')->set("custom importableFields $cacheKey", $fields);
496 }
497 self::$_importFields[$cacheKey] = $fields;
498 }
499
500 return self::$_importFields[$cacheKey];
501 }
502
503 /**
504 * Return the field ids and names (with groups) for import purpose.
505 *
506 * @param int|string $contactType Contact type
507 * @param bool $showAll
508 * If true returns all fields (includes disabled fields).
509 * @param bool $onlyParent
510 * Return fields ONLY related to basic types.
511 * @param bool $search
512 * When called from search and multiple records need to be returned.
513 * @param bool $checkPermission
514 * If false, do not include permissioning clause.
515 *
516 * @param bool $withMultiple
517 *
518 * @return array
519 */
520 public static function getFieldsForImport(
521 $contactType = 'Individual',
522 $showAll = FALSE,
523 $onlyParent = FALSE,
524 $search = FALSE,
525 $checkPermission = TRUE,
526 $withMultiple = FALSE
527 ) {
528 // Note: there are situations when we want getFieldsForImport() return fields related
529 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
530 $fields = &self::getFields($contactType,
531 $showAll,
532 FALSE,
533 NULL,
534 NULL,
535 $onlyParent,
536 FALSE,
537 $checkPermission
538 );
539
540 $importableFields = [];
541 foreach ($fields as $id => $values) {
542 // for now we should not allow multiple fields in profile / export etc, hence unsetting
543 if (!$search &&
544 (!empty($values['is_multiple']) && !$withMultiple)
545 ) {
546 continue;
547 }
548 if (!empty($values['text_length'])) {
549 $values['maxlength'] = (int) $values['text_length'];
550 }
551
552 /* generate the key for the fields array */
553
554 $key = "custom_$id";
555 $importableFields[$key] = $values;
556 $importableFields[$key]['import'] = 1;
557 }
558
559 return $importableFields;
560 }
561
562 /**
563 * Get the field id from an import key.
564 *
565 * @param string $key
566 * The key to parse.
567 *
568 * @param bool $all
569 *
570 * @return int|null
571 * The id (if exists)
572 */
573 public static function getKeyID($key, $all = FALSE) {
574 $match = [];
575 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
576 if (!$all) {
577 return $match[1];
578 }
579 else {
580 return [
581 $match[1],
582 CRM_Utils_Array::value(2, $match),
583 ];
584 }
585 }
586 return $all ? [NULL, NULL] : NULL;
587 }
588
589 /**
590 * Use the cache to get all values of a specific custom field.
591 *
592 * @param int $fieldID
593 * The custom field ID.
594 *
595 * @return CRM_Core_BAO_CustomField
596 * The field object.
597 */
598 public static function getFieldObject($fieldID) {
599 $field = new CRM_Core_BAO_CustomField();
600
601 // check if we can get the field values from the system cache
602 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
603 $cache = CRM_Utils_Cache::singleton();
604 $fieldValues = $cache->get($cacheKey);
605 if (empty($fieldValues)) {
606 $field->id = $fieldID;
607 if (!$field->find(TRUE)) {
608 CRM_Core_Error::fatal();
609 }
610
611 $fieldValues = [];
612 CRM_Core_DAO::storeValues($field, $fieldValues);
613
614 $cache->set($cacheKey, $fieldValues);
615 }
616 else {
617 $field->copyValues($fieldValues);
618 }
619
620 return $field;
621 }
622
623 /**
624 * Add a custom field to an existing form.
625 *
626 * @param CRM_Core_Form $qf
627 * Form object (reference).
628 * @param string $elementName
629 * Name of the custom field.
630 * @param int $fieldId
631 * @param bool $useRequired
632 * True if required else false.
633 * @param bool $search
634 * True if used for search else false.
635 * @param string $label
636 * Label for custom field.
637 * @return \HTML_QuickForm_Element|null
638 * @throws \CiviCRM_API3_Exception
639 */
640 public static function addQuickFormElement(
641 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
642 ) {
643 $field = self::getFieldObject($fieldId);
644 $widget = $field->html_type;
645 $element = NULL;
646 $customFieldAttributes = [];
647
648 // Custom field HTML should indicate group+field name
649 $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
650 $dataCrmCustomVal = $groupName . ':' . $field->name;
651 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
652 $field->attributes .= $dataCrmCustomAttr;
653
654 // Fixed for Issue CRM-2183
655 if ($widget == 'TextArea' && $search) {
656 $widget = 'Text';
657 }
658
659 $placeholder = $search ? ts('- any -') : ($useRequired ? ts('- select -') : ts('- none -'));
660
661 // FIXME: Why are select state/country separate widget types?
662 $isSelect = (in_array($widget, [
663 'Select',
664 'Multi-Select',
665 'Select State/Province',
666 'Multi-Select State/Province',
667 'Select Country',
668 'Multi-Select Country',
669 'CheckBox',
670 'Radio',
671 ]));
672
673 if ($isSelect) {
674 $options = $field->getOptions($search ? 'search' : 'create');
675
676 // Consolidate widget types to simplify the below switch statement
677 if ($search || (strpos($widget, 'Select') !== FALSE)) {
678 $widget = 'Select';
679 }
680
681 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
682 $selectAttributes = ['class' => 'crm-select2'];
683
684 // Search field is always multi-select
685 if ($search || strpos($field->html_type, 'Multi') !== FALSE) {
686 $selectAttributes['class'] .= ' huge';
687 $selectAttributes['multiple'] = 'multiple';
688 $selectAttributes['placeholder'] = $placeholder;
689 }
690
691 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
692 $canEditOptions = CRM_Core_Permission::check('administer CiviCRM');
693 if ($field->option_group_id && !$search && $isSelect && $canEditOptions) {
694 $customFieldAttributes += [
695 'data-api-entity' => $field->getEntity(),
696 'data-api-field' => 'custom_' . $field->id,
697 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id),
698 ];
699 $selectAttributes += $customFieldAttributes;
700 }
701 }
702
703 $rangeDataTypes = ['Int', 'Float', 'Money'];
704
705 if (!isset($label)) {
706 $label = $field->label;
707 }
708
709 // at some point in time we might want to split the below into small functions
710
711 switch ($widget) {
712 case 'Text':
713 case 'Link':
714 if ($field->is_search_range && $search && in_array($field->data_type, $rangeDataTypes)) {
715 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
716 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
717 }
718 else {
719 if ($field->text_length) {
720 $field->attributes .= ' maxlength=' . $field->text_length;
721 if ($field->text_length < 20) {
722 $field->attributes .= ' size=' . $field->text_length;
723 }
724 }
725 $element = $qf->add('text', $elementName, $label,
726 $field->attributes,
727 $useRequired && !$search
728 );
729 }
730 break;
731
732 case 'TextArea':
733 $attributes = $dataCrmCustomAttr;
734 if ($field->note_rows) {
735 $attributes .= 'rows=' . $field->note_rows;
736 }
737 else {
738 $attributes .= 'rows=4';
739 }
740 if ($field->note_columns) {
741 $attributes .= ' cols=' . $field->note_columns;
742 }
743 else {
744 $attributes .= ' cols=60';
745 }
746 if ($field->text_length) {
747 $attributes .= ' maxlength=' . $field->text_length;
748 }
749 $element = $qf->add('textarea',
750 $elementName,
751 $label,
752 $attributes,
753 $useRequired && !$search
754 );
755 break;
756
757 case 'Select Date':
758 $attr = ['data-crm-custom' => $dataCrmCustomVal];
759 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
760 $minYear = isset($field->start_date_years) ? (date('Y') - $field->start_date_years) : NULL;
761 $maxYear = isset($field->end_date_years) ? (date('Y') + $field->end_date_years) : NULL;
762
763 $params = [
764 'date' => $field->date_format,
765 'minDate' => isset($minYear) ? $minYear . '-01-01' : NULL,
766 //CRM-18487 - max date should be the last date of the year.
767 'maxDate' => isset($maxYear) ? $maxYear . '-12-31' : NULL,
768 'time' => $field->time_format ? $field->time_format * 12 : FALSE,
769 ];
770 if ($field->is_search_range && $search) {
771 $qf->add('datepicker', $elementName . '_from', $label, $attr + array('placeholder' => ts('From')), FALSE, $params);
772 $qf->add('datepicker', $elementName . '_to', NULL, $attr + array('placeholder' => ts('To')), FALSE, $params);
773 }
774 else {
775 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
776 }
777 break;
778
779 case 'Radio':
780 if ($field->is_search_range && $search && in_array($field->data_type, $rangeDataTypes)) {
781 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
782 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
783 }
784 else {
785 $choice = [];
786 parse_str($field->attributes, $radioAttributes);
787 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
788
789 foreach ($options as $v => $l) {
790 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
791 }
792 $element = $qf->addGroup($choice, $elementName, $label);
793 $optionEditKey = 'data-option-edit-path';
794 if (isset($selectAttributes[$optionEditKey])) {
795 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
796 }
797
798 if ($useRequired && !$search) {
799 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
800 }
801 else {
802 $element->setAttribute('allowClear', TRUE);
803 }
804 }
805 break;
806
807 // For all select elements
808 case 'Select':
809 if ($field->is_search_range && $search && in_array($field->data_type, $rangeDataTypes)) {
810 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
811 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
812 }
813 else {
814 if (empty($selectAttributes['multiple'])) {
815 $options = ['' => $placeholder] + $options;
816 }
817 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
818
819 // Add and/or option for fields that store multiple values
820 if ($search && self::isSerialized($field)) {
821
822 $operators = [
823 $qf->createElement('radio', NULL, '', ts('Any'), 'or', ['title' => ts('Results may contain any of the selected options')]),
824 $qf->createElement('radio', NULL, '', ts('All'), 'and', ['title' => ts('Results must have all of the selected options')]),
825 ];
826 $qf->addGroup($operators, $elementName . '_operator');
827 $qf->setDefaults([$elementName . '_operator' => 'or']);
828 }
829 }
830 break;
831
832 case 'CheckBox':
833 $check = [];
834 foreach ($options as $v => $l) {
835 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
836 }
837
838 $group = $element = $qf->addGroup($check, $elementName, $label);
839 $optionEditKey = 'data-option-edit-path';
840 if (isset($customFieldAttributes[$optionEditKey])) {
841 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
842 }
843
844 if ($useRequired && !$search) {
845 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
846 }
847 break;
848
849 case 'File':
850 // we should not build upload file in search mode
851 if ($search) {
852 return NULL;
853 }
854 $element = $qf->add(
855 strtolower($field->html_type),
856 $elementName,
857 $label,
858 $field->attributes,
859 $useRequired && !$search
860 );
861 $qf->addUploadElement($elementName);
862 break;
863
864 case 'RichTextEditor':
865 $attributes = [
866 'rows' => $field->note_rows,
867 'cols' => $field->note_columns,
868 'data-crm-custom' => $dataCrmCustomVal,
869 ];
870 if ($field->text_length) {
871 $attributes['maxlength'] = $field->text_length;
872 }
873 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
874 break;
875
876 case 'Autocomplete-Select':
877 static $customUrls = [];
878 // Fixme: why is this a string in the first place??
879 $attributes = array();
880 if ($field->attributes) {
881 foreach (explode(' ', $field->attributes) as $at) {
882 if (strpos($at, '=')) {
883 list($k, $v) = explode('=', $at);
884 $attributes[$k] = trim($v, ' "');
885 }
886 }
887 }
888 if ($field->data_type == 'ContactReference') {
889 // break if contact does not have permission to access ContactReference
890 if (!CRM_Core_Permission::check('access contact reference fields')) {
891 break;
892 }
893 $attributes['class'] = (isset($attributes['class']) ? $attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
894 $attributes['data-api-entity'] = 'Contact';
895 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
896
897 $urlParams = "context=customfield&id={$field->id}";
898 $idOfelement = $elementName;
899 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
900 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
901 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
902 // rather than layering on more hacks.
903 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
904 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') + 1)), 0, -1);
905 }
906 $customUrls[$idOfelement] = CRM_Utils_System::url('civicrm/ajax/contactref',
907 $urlParams,
908 FALSE, NULL, FALSE
909 );
910
911 }
912 else {
913 // FIXME: This won't work with customFieldOptions hook
914 $attributes += [
915 'entity' => 'OptionValue',
916 'placeholder' => $placeholder,
917 'multiple' => $search,
918 'api' => [
919 'params' => ['option_group_id' => $field->option_group_id, 'is_active' => 1],
920 ],
921 ];
922 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
923 }
924
925 $qf->assign('customUrls', $customUrls);
926 break;
927 }
928
929 switch ($field->data_type) {
930 case 'Int':
931 // integers will have numeric rule applied to them.
932 if ($field->is_search_range && $search) {
933 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', [1 => $label]), 'integer');
934 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', [1 => $label]), 'integer');
935 }
936 elseif ($widget == 'Text') {
937 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', [1 => $label]), 'integer');
938 }
939 break;
940
941 case 'Float':
942 if ($field->is_search_range && $search) {
943 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', [1 => $label]), 'numeric');
944 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', [1 => $label]), 'numeric');
945 }
946 elseif ($widget == 'Text') {
947 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', [1 => $label]), 'numeric');
948 }
949 break;
950
951 case 'Money':
952 if ($field->is_search_range && $search) {
953 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
954 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
955 }
956 elseif ($widget == 'Text') {
957 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
958 }
959 break;
960
961 case 'Link':
962 $element->setAttribute('class', "url");
963 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
964 break;
965 }
966 if ($field->is_view && !$search) {
967 $qf->freeze($elementName);
968 }
969 return $element;
970 }
971
972 /**
973 * Delete the Custom Field.
974 *
975 * @param object $field
976 * The field object.
977 */
978 public static function deleteField($field) {
979 CRM_Utils_System::flushCache();
980
981 // first delete the custom option group and values associated with this field
982 if ($field->option_group_id) {
983 //check if option group is related to any other field, if
984 //not delete the option group and related option values
985 self::checkOptionGroup($field->option_group_id);
986 }
987
988 // next drop the column from the custom value table
989 self::createField($field, 'delete');
990
991 $field->delete();
992 CRM_Core_BAO_UFField::delUFField($field->id);
993 CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_CustomField');
994
995 CRM_Utils_Hook::post('delete', 'CustomField', $field->id, $field);
996 }
997
998 /**
999 * @param string|int|array|null $value
1000 * @param CRM_Core_BAO_CustomField|int|array|string $field
1001 * @param int $entityId
1002 *
1003 * @return string
1004 *
1005 * @throws \CRM_Core_Exception
1006 */
1007 public static function displayValue($value, $field, $entityId = NULL) {
1008 $field = is_array($field) ? $field['id'] : $field;
1009 $fieldId = is_object($field) ? $field->id : (int) str_replace('custom_', '', $field);
1010
1011 if (!$fieldId) {
1012 throw new CRM_Core_Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1013 }
1014
1015 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1016 $field = self::getFieldObject($fieldId);
1017 }
1018
1019 $fieldInfo = ['options' => $field->getOptions()] + (array) $field;
1020
1021 $displayValue = self::formatDisplayValue($value, $fieldInfo, $entityId);
1022
1023 // Call hook to alter display value.
1024 CRM_Utils_Hook::alterCustomFieldDisplayValue($displayValue, $value, $entityId, $fieldInfo);
1025
1026 return $displayValue;
1027 }
1028
1029 /**
1030 * Lower-level logic for rendering a custom field value
1031 *
1032 * @param string|array $value
1033 * @param array $field
1034 * @param int|null $entityId
1035 *
1036 * @return string
1037 */
1038 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1039
1040 if (self::isSerialized($field) && !is_array($value)) {
1041 $value = CRM_Utils_Array::explodePadded($value);
1042 }
1043 // CRM-12989 fix
1044 if ($field['html_type'] == 'CheckBox' && $value) {
1045 $value = CRM_Utils_Array::convertCheckboxFormatToArray($value);
1046 }
1047
1048 $display = is_array($value) ? implode(', ', $value) : (string) $value;
1049
1050 switch ($field['html_type']) {
1051
1052 case 'Select':
1053 case 'Autocomplete-Select':
1054 case 'Radio':
1055 case 'Select Country':
1056 case 'Select State/Province':
1057 case 'CheckBox':
1058 case 'Multi-Select':
1059 case 'Multi-Select State/Province':
1060 case 'Multi-Select Country':
1061 if ($field['data_type'] == 'ContactReference' && $value) {
1062 if (is_numeric($value)) {
1063 $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1064 }
1065 else {
1066 $display = $value;
1067 }
1068 }
1069 elseif (is_array($value)) {
1070 $v = [];
1071 foreach ($value as $key => $val) {
1072 $v[] = $field['options'][$val] ?? NULL;
1073 }
1074 $display = implode(', ', $v);
1075 }
1076 else {
1077 $display = CRM_Utils_Array::value($value, $field['options'], '');
1078 }
1079 break;
1080
1081 case 'Select Date':
1082 $customFormat = NULL;
1083
1084 // FIXME: Are there any legitimate reasons why $value would be an array?
1085 // Or should we throw an exception here if it is?
1086 $value = is_array($value) ? CRM_Utils_Array::first($value) : $value;
1087
1088 $actualPHPFormats = CRM_Utils_Date::datePluginToPHPFormats();
1089 $format = $field['date_format'] ?? NULL;
1090
1091 if ($format) {
1092 if (array_key_exists($format, $actualPHPFormats)) {
1093 $customTimeFormat = (array) $actualPHPFormats[$format];
1094 switch (CRM_Utils_Array::value('time_format', $field)) {
1095 case 1:
1096 $customTimeFormat[] = 'g:iA';
1097 break;
1098
1099 case 2:
1100 $customTimeFormat[] = 'G:i';
1101 break;
1102
1103 default:
1104 //If time is not selected remove time from value.
1105 $value = $value ? date('Y-m-d', strtotime($value)) : '';
1106 }
1107 $customFormat = implode(" ", $customTimeFormat);
1108 }
1109 }
1110 $display = CRM_Utils_Date::processDate($value, NULL, FALSE, $customFormat);
1111 break;
1112
1113 case 'File':
1114 // In the context of displaying a profile, show file/image
1115 if ($value) {
1116 if ($entityId) {
1117 if (CRM_Utils_Rule::positiveInteger($value)) {
1118 $fileId = $value;
1119 }
1120 else {
1121 $fileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1122 }
1123 $url = self::getFileURL($entityId, $field['id'], $fileId);
1124 if ($url) {
1125 $display = $url['file_url'];
1126 }
1127 }
1128 else {
1129 // In other contexts show a paperclip icon
1130 if (CRM_Utils_Rule::integer($value)) {
1131 $icons = CRM_Core_BAO_File::paperIconAttachment('*', $value);
1132
1133 $file_description = '';
1134 try {
1135 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1136 }
1137 catch (CiviCRM_API3_Exception $dontcare) {
1138 // don't care
1139 }
1140
1141 $display = "{$icons[$value]}{$file_description}";
1142 }
1143 else {
1144 //CRM-18396, if filename is passed instead
1145 $display = $value;
1146 }
1147 }
1148 }
1149 break;
1150
1151 case 'Link':
1152 $display = $display ? "<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1153 break;
1154
1155 case 'TextArea':
1156 $display = nl2br($display);
1157 break;
1158
1159 case 'Text':
1160 if ($field['data_type'] == 'Money' && isset($value)) {
1161 // $value can also be an array(while using IN operator from search builder or api).
1162 foreach ((array) $value as $val) {
1163 $disp[] = CRM_Utils_Money::format($val, NULL, NULL, TRUE);
1164 }
1165 $display = implode(', ', $disp);
1166 }
1167 break;
1168 }
1169 return $display;
1170 }
1171
1172 /**
1173 * Set default values for custom data used in profile.
1174 *
1175 * @param int $customFieldId
1176 * Custom field id.
1177 * @param string $elementName
1178 * Custom field name.
1179 * @param array $defaults
1180 * Associated array of fields.
1181 * @param int $contactId
1182 * Contact id.
1183 * @param int $mode
1184 * Profile mode.
1185 * @param mixed $value
1186 * If passed - dont fetch value from db,.
1187 * just format the given value
1188 */
1189 public static function setProfileDefaults(
1190 $customFieldId,
1191 $elementName,
1192 &$defaults,
1193 $contactId = NULL,
1194 $mode = NULL,
1195 $value = NULL
1196 ) {
1197 //get the type of custom field
1198 $customField = new CRM_Core_BAO_CustomField();
1199 $customField->id = $customFieldId;
1200 $customField->find(TRUE);
1201
1202 if (!$contactId) {
1203 if ($mode == CRM_Profile_Form::MODE_CREATE) {
1204 $value = $customField->default_value;
1205 }
1206 }
1207 else {
1208 if (!isset($value)) {
1209 $info = self::getTableColumnGroup($customFieldId);
1210 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1211 $result = CRM_Core_DAO::executeQuery($query);
1212 if ($result->fetch()) {
1213 $value = $result->value;
1214 }
1215 }
1216
1217 if ($customField->data_type == 'Country') {
1218 if (!$value) {
1219 $config = CRM_Core_Config::singleton();
1220 if ($config->defaultContactCountry) {
1221 $value = CRM_Core_BAO_Country::defaultContactCountry();
1222 }
1223 }
1224 }
1225 }
1226
1227 //set defaults if mode is registration
1228 if (!trim($value) &&
1229 ($value !== 0) &&
1230 (!in_array($mode, [CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH]))
1231 ) {
1232 $value = $customField->default_value;
1233 }
1234
1235 if ($customField->data_type == 'Money' && isset($value)) {
1236 $value = number_format($value, 2);
1237 }
1238 if (self::isSerialized($customField)) {
1239 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
1240 $defaults[$elementName] = [];
1241 $checkedValue = CRM_Utils_Array::explodePadded($value);
1242 foreach ($customOption as $val) {
1243 if (in_array($val['value'], $checkedValue)) {
1244 if ($customField->html_type == 'CheckBox') {
1245 $defaults[$elementName][$val['value']] = 1;
1246 }
1247 else {
1248 $defaults[$elementName][$val['value']] = $val['value'];
1249 }
1250 }
1251 }
1252 }
1253 else {
1254 $defaults[$elementName] = $value;
1255 }
1256 }
1257
1258 /**
1259 * Get file url.
1260 *
1261 * @param int $contactID
1262 * @param int $cfID
1263 * @param int $fileID
1264 * @param bool $absolute
1265 *
1266 * @param string $multiRecordWhereClause
1267 *
1268 * @return array
1269 */
1270 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1271 if ($contactID) {
1272 if (!$fileID) {
1273 $params = ['id' => $cfID];
1274 $defaults = [];
1275 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1276 $columnName = $defaults['column_name'];
1277
1278 //table name of custom data
1279 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1280 $defaults['custom_group_id'],
1281 'table_name', 'id'
1282 );
1283
1284 //query to fetch id from civicrm_file
1285 if ($multiRecordWhereClause) {
1286 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1287 }
1288 else {
1289 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1290 }
1291 $fileID = CRM_Core_DAO::singleValueQuery($query);
1292 }
1293
1294 $result = [];
1295 if ($fileID) {
1296 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1297 $fileID,
1298 'mime_type',
1299 'id'
1300 );
1301 $result['file_id'] = $fileID;
1302
1303 if ($fileType == 'image/jpeg' ||
1304 $fileType == 'image/pjpeg' ||
1305 $fileType == 'image/gif' ||
1306 $fileType == 'image/x-png' ||
1307 $fileType == 'image/png'
1308 ) {
1309 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1310 $fileID,
1311 'entity_id',
1312 'file_id'
1313 );
1314 list($path) = CRM_Core_BAO_File::path($fileID, $entityId);
1315 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileID);
1316 $url = CRM_Utils_System::url('civicrm/file',
1317 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1318 $absolute, NULL, TRUE, TRUE
1319 );
1320 $result['file_url'] = CRM_Utils_File::getFileURL($path, $fileType, $url);
1321 }
1322 // for non image files
1323 else {
1324 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1325 $fileID,
1326 'uri'
1327 );
1328 $fileHash = CRM_Core_BAO_File::generateFileHash($contactID, $fileID);
1329 $url = CRM_Utils_System::url('civicrm/file',
1330 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1331 $absolute, NULL, TRUE, TRUE
1332 );
1333 $result['file_url'] = CRM_Utils_File::getFileURL($uri, $fileType, $url);
1334 }
1335 }
1336 return $result;
1337 }
1338 }
1339
1340 /**
1341 * Format custom fields before inserting.
1342 *
1343 * @param int $customFieldId
1344 * Custom field id.
1345 * @param array $customFormatted
1346 * Formatted array.
1347 * @param mixed $value
1348 * Value of custom field.
1349 * @param string $customFieldExtend
1350 * Custom field extends.
1351 * @param int $customValueId
1352 * Custom option value id.
1353 * @param int $entityId
1354 * Entity id (contribution, membership...).
1355 * @param bool $inline
1356 * Consider inline custom groups only.
1357 * @param bool $checkPermission
1358 * If false, do not include permissioning clause.
1359 * @param bool $includeViewOnly
1360 * If true, fields marked 'View Only' are included. Required for APIv3.
1361 *
1362 * @return array|NULL
1363 * formatted custom field array
1364 */
1365 public static function formatCustomField(
1366 $customFieldId, &$customFormatted, $value,
1367 $customFieldExtend, $customValueId = NULL,
1368 $entityId = NULL,
1369 $inline = FALSE,
1370 $checkPermission = TRUE,
1371 $includeViewOnly = FALSE
1372 ) {
1373 //get the custom fields for the entity
1374 //subtype and basic type
1375 $customDataSubType = NULL;
1376 if ($customFieldExtend) {
1377 // This is the case when getFieldsForImport() requires fields
1378 // of subtype and its parent.CRM-5143
1379 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1380 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType::subTypes(), (array) $customFieldExtend);
1381 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1382 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1383 if (is_array($customFieldExtend)) {
1384 $customFieldExtend = array_unique(array_values($customFieldExtend));
1385 }
1386 }
1387 }
1388
1389 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1390 FALSE,
1391 $inline,
1392 $customDataSubType,
1393 NULL,
1394 FALSE,
1395 FALSE,
1396 $checkPermission
1397 );
1398
1399 if (!array_key_exists($customFieldId, $customFields)) {
1400 return NULL;
1401 }
1402
1403 // return if field is a 'code' field
1404 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1405 return NULL;
1406 }
1407
1408 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1409
1410 if (!$customValueId &&
1411 // we always create new entites for is_multiple unless specified
1412 !$customFields[$customFieldId]['is_multiple'] &&
1413 $entityId
1414 ) {
1415 $query = "
1416 SELECT id
1417 FROM $tableName
1418 WHERE entity_id={$entityId}";
1419
1420 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1421 }
1422
1423 //fix checkbox, now check box always submits values
1424 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1425 if ($value) {
1426 // Note that only during merge this is not an array, and you can directly use value
1427 if (is_array($value)) {
1428 $selectedValues = [];
1429 foreach ($value as $selId => $val) {
1430 if ($val) {
1431 $selectedValues[] = $selId;
1432 }
1433 }
1434 if (!empty($selectedValues)) {
1435 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1436 $selectedValues
1437 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1438 }
1439 else {
1440 $value = '';
1441 }
1442 }
1443 }
1444 }
1445 elseif (self::isSerialized($customFields[$customFieldId])) {
1446 $value = $value ? CRM_Utils_Array::implodePadded($value) : '';
1447 }
1448
1449 if (self::isSerialized($customFields[$customFieldId]) &&
1450 $customFields[$customFieldId]['data_type'] == 'String' &&
1451 !empty($customFields[$customFieldId]['text_length']) &&
1452 !empty($value)
1453 ) {
1454 // lets make sure that value is less than the length, else we'll
1455 // be losing some data, CRM-7481
1456 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1457 // need to do a few things here
1458
1459 // 1. lets find a new length
1460 $newLength = $customFields[$customFieldId]['text_length'];
1461 $minLength = strlen($value);
1462 while ($newLength < $minLength) {
1463 $newLength = $newLength * 2;
1464 }
1465
1466 // set the custom field meta data to have a length larger than value
1467 // alter the custom value table column to match this length
1468 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1469 }
1470 }
1471
1472 $date = NULL;
1473 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1474 if (!CRM_Utils_System::isNull($value)) {
1475 $format = $customFields[$customFieldId]['date_format'];
1476 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1477 }
1478 $value = $date;
1479 }
1480
1481 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1482 $customFields[$customFieldId]['data_type'] == 'Money'
1483 ) {
1484 if (!$value) {
1485 $value = 0;
1486 }
1487
1488 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1489 $value = CRM_Utils_Rule::cleanMoney($value);
1490 }
1491 }
1492
1493 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1494 $customFields[$customFieldId]['data_type'] == 'Country'
1495 ) &&
1496 empty($value)
1497 ) {
1498 // CRM-3415
1499 $value = 0;
1500 }
1501
1502 $fileID = NULL;
1503
1504 if ($customFields[$customFieldId]['data_type'] == 'File') {
1505 if (empty($value)) {
1506 return;
1507 }
1508
1509 $config = CRM_Core_Config::singleton();
1510
1511 // If we are already passing the file id as a value then retrieve and set the file data
1512 if (CRM_Utils_Rule::integer($value)) {
1513 $fileDAO = new CRM_Core_DAO_File();
1514 $fileDAO->id = $value;
1515 $fileDAO->find(TRUE);
1516 if ($fileDAO->N) {
1517 $fileID = $value;
1518 $fName = $fileDAO->uri;
1519 $mimeType = $fileDAO->mime_type;
1520 }
1521 }
1522 else {
1523 $fName = $value['name'];
1524 $mimeType = $value['type'];
1525 }
1526
1527 $filename = pathinfo($fName, PATHINFO_BASENAME);
1528
1529 // rename this file to go into the secure directory only if
1530 // user has uploaded new file not existing verfied on the basis of $fileID
1531 if (empty($fileID) && !rename($fName, $config->customFileUploadDir . $filename)) {
1532 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
1533 }
1534
1535 if ($customValueId && empty($fileID)) {
1536 $query = "
1537 SELECT $columnName
1538 FROM $tableName
1539 WHERE id = %1";
1540 $params = [1 => [$customValueId, 'Integer']];
1541 $fileID = CRM_Core_DAO::singleValueQuery($query, $params);
1542 }
1543
1544 $fileDAO = new CRM_Core_DAO_File();
1545
1546 if ($fileID) {
1547 $fileDAO->id = $fileID;
1548 }
1549
1550 $fileDAO->uri = $filename;
1551 $fileDAO->mime_type = $mimeType;
1552 $fileDAO->upload_date = date('YmdHis');
1553 $fileDAO->save();
1554 $fileID = $fileDAO->id;
1555 $value = $filename;
1556 }
1557
1558 if (!is_array($customFormatted)) {
1559 $customFormatted = [];
1560 }
1561
1562 if (!array_key_exists($customFieldId, $customFormatted)) {
1563 $customFormatted[$customFieldId] = [];
1564 }
1565
1566 $index = -1;
1567 if ($customValueId) {
1568 $index = $customValueId;
1569 }
1570
1571 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1572 $customFormatted[$customFieldId][$index] = [];
1573 }
1574 $customFormatted[$customFieldId][$index] = [
1575 'id' => $customValueId > 0 ? $customValueId : NULL,
1576 'value' => $value,
1577 'type' => $customFields[$customFieldId]['data_type'],
1578 'custom_field_id' => $customFieldId,
1579 'custom_group_id' => $groupID,
1580 'table_name' => $tableName,
1581 'column_name' => $columnName,
1582 'file_id' => $fileID,
1583 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1584 ];
1585
1586 //we need to sort so that custom fields are created in the order of entry
1587 krsort($customFormatted[$customFieldId]);
1588 return $customFormatted;
1589 }
1590
1591 /**
1592 * Get default custom table schema.
1593 *
1594 * @param array $params
1595 *
1596 * @return array
1597 */
1598 public static function defaultCustomTableSchema($params) {
1599 // add the id and extends_id
1600 $table = [
1601 'name' => $params['name'],
1602 'is_multiple' => $params['is_multiple'],
1603 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1604 'fields' => [
1605 [
1606 'name' => 'id',
1607 'type' => 'int unsigned',
1608 'primary' => TRUE,
1609 'required' => TRUE,
1610 'attributes' => 'AUTO_INCREMENT',
1611 'comment' => 'Default MySQL primary key',
1612 ],
1613 [
1614 'name' => 'entity_id',
1615 'type' => 'int unsigned',
1616 'required' => TRUE,
1617 'comment' => 'Table that this extends',
1618 'fk_table_name' => $params['extends_name'],
1619 'fk_field_name' => 'id',
1620 'fk_attributes' => 'ON DELETE CASCADE',
1621 ],
1622 ],
1623 ];
1624
1625 if (!$params['is_multiple']) {
1626 $table['indexes'] = [
1627 [
1628 'unique' => TRUE,
1629 'field_name_1' => 'entity_id',
1630 ],
1631 ];
1632 }
1633 return $table;
1634 }
1635
1636 /**
1637 * Create custom field.
1638 *
1639 * @param CRM_Core_DAO_CustomField $field
1640 * @param string $operation
1641 */
1642 public static function createField($field, $operation) {
1643 $sql = str_repeat(' ', 8);
1644 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id, 'table_name');
1645 $sql .= "ALTER TABLE " . $tableName;
1646 $sql .= self::getAlterFieldSQL($field, $operation);
1647
1648 // CRM-7007: do not i18n-rewrite this query
1649 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1650
1651 $config = CRM_Core_Config::singleton();
1652 if ($config->logging) {
1653 // CRM-16717 not sure why this was originally limited to add.
1654 // For example custom tables can have field length changes - which need to flow through to logging.
1655 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1656 if ($operation === 'add' || $operation === 'modify') {
1657 $logging = new CRM_Logging_Schema();
1658 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name]]);
1659 }
1660 }
1661
1662 Civi::service('sql_triggers')->rebuild($tableName, TRUE);
1663 }
1664
1665 /**
1666 * @param CRM_Core_DAO_CustomField $field
1667 * @param string $operation
1668 *
1669 * @return bool
1670 */
1671 public static function getAlterFieldSQL($field, $operation) {
1672 $indexExist = $operation === 'add' ? FALSE : CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $field->id, 'is_searchable');
1673 $params = self::prepareCreateParams($field, $operation);
1674 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1675 // a function only used by Custom Field creation...
1676 $params['required'] = FALSE;
1677 return CRM_Core_BAO_SchemaHandler::getFieldAlterSQL($params, $indexExist);
1678 }
1679
1680 /**
1681 * Determine whether it would be safe to move a field.
1682 *
1683 * @param int $fieldID
1684 * FK to civicrm_custom_field.
1685 * @param int $newGroupID
1686 * FK to civicrm_custom_group.
1687 *
1688 * @return array
1689 * array(string) or TRUE
1690 */
1691 public static function _moveFieldValidate($fieldID, $newGroupID) {
1692 $errors = [];
1693
1694 $field = new CRM_Core_DAO_CustomField();
1695 $field->id = $fieldID;
1696 if (!$field->find(TRUE)) {
1697 $errors['fieldID'] = 'Invalid ID for custom field';
1698 return $errors;
1699 }
1700
1701 $oldGroup = new CRM_Core_DAO_CustomGroup();
1702 $oldGroup->id = $field->custom_group_id;
1703 if (!$oldGroup->find(TRUE)) {
1704 $errors['fieldID'] = 'Invalid ID for old custom group';
1705 return $errors;
1706 }
1707
1708 $newGroup = new CRM_Core_DAO_CustomGroup();
1709 $newGroup->id = $newGroupID;
1710 if (!$newGroup->find(TRUE)) {
1711 $errors['newGroupID'] = 'Invalid ID for new custom group';
1712 return $errors;
1713 }
1714
1715 $query = "
1716 SELECT b.id
1717 FROM civicrm_custom_field a
1718 INNER JOIN civicrm_custom_field b
1719 WHERE a.id = %1
1720 AND a.label = b.label
1721 AND b.custom_group_id = %2
1722 ";
1723 $params = [
1724 1 => [$field->id, 'Integer'],
1725 2 => [$newGroup->id, 'Integer'],
1726 ];
1727 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1728 if ($count > 0) {
1729 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1730 }
1731
1732 $tableName = $oldGroup->table_name;
1733 $columnName = $field->column_name;
1734
1735 $query = "
1736 SELECT count(*)
1737 FROM $tableName
1738 WHERE $columnName is not null
1739 ";
1740 $count = CRM_Core_DAO::singleValueQuery($query);
1741 if ($count > 0) {
1742 $query = "
1743 SELECT extends
1744 FROM civicrm_custom_group
1745 WHERE id IN ( %1, %2 )
1746 ";
1747 $params = [
1748 1 => [$oldGroup->id, 'Integer'],
1749 2 => [$newGroup->id, 'Integer'],
1750 ];
1751
1752 $dao = CRM_Core_DAO::executeQuery($query, $params);
1753 $extends = [];
1754 while ($dao->fetch()) {
1755 $extends[] = $dao->extends;
1756 }
1757 if ($extends[0] != $extends[1]) {
1758 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1759 }
1760 }
1761
1762 return empty($errors) ? TRUE : $errors;
1763 }
1764
1765 /**
1766 * Move a custom data field from one group (table) to another.
1767 *
1768 * @param int $fieldID
1769 * FK to civicrm_custom_field.
1770 * @param int $newGroupID
1771 * FK to civicrm_custom_group.
1772 */
1773 public static function moveField($fieldID, $newGroupID) {
1774 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
1775 if (TRUE !== $validation) {
1776 CRM_Core_Error::fatal(implode(' ', $validation));
1777 }
1778 $field = new CRM_Core_DAO_CustomField();
1779 $field->id = $fieldID;
1780 $field->find(TRUE);
1781
1782 $newGroup = new CRM_Core_DAO_CustomGroup();
1783 $newGroup->id = $newGroupID;
1784 $newGroup->find(TRUE);
1785
1786 $oldGroup = new CRM_Core_DAO_CustomGroup();
1787 $oldGroup->id = $field->custom_group_id;
1788 $oldGroup->find(TRUE);
1789
1790 $add = clone$field;
1791 $add->custom_group_id = $newGroup->id;
1792 self::createField($add, 'add');
1793
1794 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1795 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1796 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1797 ";
1798 CRM_Core_DAO::executeQuery($sql);
1799
1800 $del = clone$field;
1801 $del->custom_group_id = $oldGroup->id;
1802 self::createField($del, 'delete');
1803
1804 $add->save();
1805
1806 CRM_Utils_System::flushCache();
1807 }
1808
1809 /**
1810 * Create an option value for a custom field option group ID.
1811 *
1812 * @param array $params
1813 * @param string $value
1814 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1815 * @param string $index
1816 * @param string $dataType
1817 */
1818 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup $optionGroup, $index, $dataType) {
1819 if (strlen(trim($value))) {
1820 $optionValue = new CRM_Core_DAO_OptionValue();
1821 $optionValue->option_group_id = $optionGroup->id;
1822 $optionValue->label = $params['option_label'][$index];
1823 $optionValue->name = $params['option_name'][$index] ?? CRM_Utils_String::titleToVar($params['option_label'][$index]);
1824 switch ($dataType) {
1825 case 'Money':
1826 $optionValue->value = CRM_Utils_Rule::cleanMoney($value);
1827 break;
1828
1829 case 'Int':
1830 $optionValue->value = intval($value);
1831 break;
1832
1833 case 'Float':
1834 $optionValue->value = floatval($value);
1835 break;
1836
1837 default:
1838 $optionValue->value = trim($value);
1839 }
1840
1841 $optionValue->weight = $params['option_weight'][$index];
1842 $optionValue->is_active = $params['option_status'][$index] ?? FALSE;
1843 $optionValue->description = $params['option_description'][$index] ?? NULL;
1844 $optionValue->color = $params['option_color'][$index] ?? NULL;
1845 $optionValue->icon = $params['option_icon'][$index] ?? NULL;
1846 $optionValue->save();
1847 }
1848 }
1849
1850 /**
1851 * Prepare for the create operation.
1852 *
1853 * Munge params, create the option values if needed.
1854 *
1855 * This could be called by a single create or a batchCreate.
1856 *
1857 * @param array $params
1858 *
1859 * @return array
1860 */
1861 protected static function prepareCreate($params) {
1862 $op = empty($params['id']) ? 'create' : 'edit';
1863 CRM_Utils_Hook::pre($op, 'CustomField', CRM_Utils_Array::value('id', $params), $params);
1864 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1865 if ($op === 'create') {
1866 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
1867 if (!isset($params['column_name'])) {
1868 // if add mode & column_name not present, calculate it.
1869 $params['column_name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 32));
1870 }
1871 if (!isset($params['name'])) {
1872 $params['name'] = CRM_Utils_String::munge($params['label'], '_', 64);
1873 }
1874 }
1875 else {
1876 $params['column_name'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1877 }
1878
1879 $htmlType = $params['html_type'] ?? NULL;
1880 $dataType = $params['data_type'] ?? NULL;
1881
1882 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1883 $params['date_format'] = Civi::settings()->get('dateInputFormat');
1884 }
1885
1886 if ($htmlType === 'CheckBox' || $htmlType === 'Multi-Select') {
1887 if (isset($params['default_checkbox_option'])) {
1888 $defaultArray = [];
1889 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1890 if ($params['option_value'][$v]) {
1891 $defaultArray[] = $params['option_value'][$v];
1892 }
1893 }
1894
1895 if (!empty($defaultArray)) {
1896 // also add the separator before and after the value per new convention (CRM-1604)
1897 $params['default_value'] = CRM_Utils_Array::implodePadded($defaultArray);
1898 }
1899 }
1900 else {
1901 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1902 $params['default_value'] = $params['option_value'][$params['default_option']];
1903 }
1904 }
1905 }
1906
1907 // create any option group & values if required
1908 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1909 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
1910 //CRM-16659: if option_value then create an option group for this custom field.
1911 if ($params['option_type'] == 1 && (empty($params['option_group_id']) || !empty($params['option_value']))) {
1912 // first create an option group for this custom group
1913 $optionGroup = new CRM_Core_DAO_OptionGroup();
1914 $optionGroup->name = "{$params['column_name']}_" . date('YmdHis');
1915 $optionGroup->title = $params['label'];
1916 $optionGroup->is_active = 1;
1917 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1918 $optionGroup->is_reserved = 0;
1919 $optionGroup->data_type = $dataType;
1920 $optionGroup->save();
1921 $params['option_group_id'] = $optionGroup->id;
1922 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1923 foreach ($params['option_value'] as $k => $v) {
1924 self::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1925 }
1926 }
1927 }
1928 }
1929
1930 // check for orphan option groups
1931 if (!empty($params['option_group_id'])) {
1932 if (!empty($params['id'])) {
1933 self::fixOptionGroups($params['id'], $params['option_group_id']);
1934 }
1935
1936 // if we do not have a default value
1937 // retrieve it from one of the other custom fields which use this option group
1938 if (empty($params['default_value'])) {
1939 //don't insert only value separator as default value, CRM-4579
1940 $defaultValue = self::getOptionGroupDefault($params['option_group_id'], $htmlType);
1941
1942 if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaultValue))) {
1943 $params['default_value'] = $defaultValue;
1944 }
1945 }
1946 }
1947
1948 // Set default textarea attributes
1949 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
1950 $params['attributes'] = 'rows=4, cols=60';
1951 }
1952 return $params;
1953 }
1954
1955 /**
1956 * Create database entry for custom field and related option groups.
1957 *
1958 * @param array $params
1959 *
1960 * @return CRM_Core_DAO_CustomField
1961 */
1962 protected static function createCustomFieldRecord($params) {
1963 $transaction = new CRM_Core_Transaction();
1964 $params = self::prepareCreate($params);
1965
1966 $customField = new CRM_Core_DAO_CustomField();
1967 $customField->copyValues($params);
1968 $customField->save();
1969
1970 //create/drop the index when we toggle the is_searchable flag
1971 $op = empty($params['id']) ? 'add' : 'modify';
1972 if ($op !== 'modify') {
1973 if ($params['is_append_field_id_to_column_name']) {
1974 $params['column_name'] .= "_{$customField->id}";
1975 }
1976 $customField->column_name = $params['column_name'];
1977 $customField->save();
1978 }
1979
1980 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
1981 $transaction->commit();
1982
1983 // make sure all values are present in the object for further processing
1984 $customField->find(TRUE);
1985 return $customField;
1986 }
1987
1988 /**
1989 * Move custom data from one contact to another.
1990 *
1991 * This is currently the start of a refactoring. The theory is each
1992 * entity could have a 'move' function with a DAO default one to fall back on.
1993 *
1994 * At the moment this only does a small part of the process - ie deleting a file field that
1995 * is about to be overwritten. However, the goal is the whole process around the move for
1996 * custom data should be in here.
1997 *
1998 * This is currently called by the merge class but it makes sense that api could
1999 * expose move actions as moving (e.g) contributions feels like a common
2000 * ask that should be handled by the form layer.
2001 *
2002 * @param int $oldContactID
2003 * @param int $newContactID
2004 * @param int[] $fieldIDs
2005 * Optional list field ids to move.
2006 *
2007 * @throws \CiviCRM_API3_Exception
2008 * @throws \Exception
2009 */
2010 public function move($oldContactID, $newContactID, $fieldIDs) {
2011 if (empty($fieldIDs)) {
2012 return;
2013 }
2014 $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'];
2015 $return = [];
2016 foreach ($fieldIDs as $fieldID) {
2017 $return[] = 'custom_' . $fieldID;
2018 }
2019 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2020 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2021
2022 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2023 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2024 $fieldTypesNotHandledInMergeAttempt = ['File'];
2025 foreach ($fields as $field) {
2026 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2027 if ($field['data_type'] === 'File' && !$isMultiple) {
2028 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2029 CRM_Core_BAO_File::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2030 }
2031 if (!empty($oldContact['custom_' . $field['id']])) {
2032 CRM_Core_DAO::executeQuery("
2033 UPDATE civicrm_entity_file
2034 SET entity_id = $newContactID
2035 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2036 );
2037 }
2038 }
2039 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2040 CRM_Core_DAO::executeQuery(
2041 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2042 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2043 ON DUPLICATE KEY UPDATE
2044 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2045 ");
2046 }
2047 }
2048 }
2049
2050 /**
2051 * Get the database table name and column name for a custom field.
2052 *
2053 * @param int $fieldID
2054 * The fieldID of the custom field.
2055 * @param bool $force
2056 * Force the sql to be run again (primarily used for tests).
2057 *
2058 * @return array
2059 * fatal is fieldID does not exists, else array of tableName, columnName
2060 * @throws \Exception
2061 */
2062 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2063 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2064 $cache = CRM_Utils_Cache::singleton();
2065 $fieldValues = $cache->get($cacheKey);
2066 if (empty($fieldValues) || $force) {
2067 $query = "
2068 SELECT cg.table_name, cf.column_name, cg.id
2069 FROM civicrm_custom_group cg,
2070 civicrm_custom_field cf
2071 WHERE cf.custom_group_id = cg.id
2072 AND cf.id = %1";
2073 $params = [1 => [$fieldID, 'Integer']];
2074 $dao = CRM_Core_DAO::executeQuery($query, $params);
2075
2076 if (!$dao->fetch()) {
2077 CRM_Core_Error::fatal();
2078 }
2079 $fieldValues = [$dao->table_name, $dao->column_name, $dao->id];
2080 $cache->set($cacheKey, $fieldValues);
2081 }
2082 return $fieldValues;
2083 }
2084
2085 /**
2086 * Get custom option groups.
2087 *
2088 * @deprecated Use the API OptionGroup.get
2089 *
2090 * @param array $includeFieldIds
2091 * Ids of custom fields for which option groups must be included.
2092 *
2093 * Currently this is required in the cases where option groups are to be included
2094 * for inactive fields : CRM-5369
2095 *
2096 * @return mixed
2097 */
2098 public static function customOptionGroup($includeFieldIds = NULL) {
2099 static $customOptionGroup = NULL;
2100
2101 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
2102 if ($cacheKey == 'force') {
2103 $customOptionGroup[$cacheKey] = NULL;
2104 }
2105
2106 if (empty($customOptionGroup[$cacheKey])) {
2107 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2108
2109 //support for single as well as array format.
2110 if (!empty($includeFieldIds)) {
2111 if (is_array($includeFieldIds)) {
2112 $includeFieldIds = implode(',', $includeFieldIds);
2113 }
2114 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2115 }
2116
2117 $query = "
2118 SELECT g.id, g.title
2119 FROM civicrm_option_group g
2120 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2121 WHERE {$whereClause}";
2122
2123 $dao = CRM_Core_DAO::executeQuery($query);
2124 while ($dao->fetch()) {
2125 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
2126 }
2127 }
2128
2129 return $customOptionGroup[$cacheKey];
2130 }
2131
2132 /**
2133 * Get defaults for new entity.
2134 *
2135 * @return array
2136 */
2137 public static function getDefaults() {
2138 return [
2139 'is_required' => FALSE,
2140 'is_searchable' => FALSE,
2141 'in_selector' => FALSE,
2142 'is_search_range' => FALSE,
2143 //CRM-15792 - Custom field gets disabled if is_active not set
2144 // this would ideally be a mysql default.
2145 'is_active' => TRUE,
2146 'is_view' => FALSE,
2147 ];
2148 }
2149
2150 /**
2151 * Fix orphan groups.
2152 *
2153 * @param int $customFieldId
2154 * Custom field id.
2155 * @param int $optionGroupId
2156 * Option group id.
2157 */
2158 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2159 // check if option group belongs to any custom Field else delete
2160 // get the current option group
2161 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2162 $customFieldId,
2163 'option_group_id'
2164 );
2165 // get the updated option group
2166 // if both are same return
2167 if (!$currentOptionGroupId || $currentOptionGroupId == $optionGroupId) {
2168 return;
2169 }
2170
2171 // check if option group is related to any other field
2172 self::checkOptionGroup($currentOptionGroupId);
2173 }
2174
2175 /**
2176 * Check if option group is related to more than one custom field.
2177 *
2178 * @param int $optionGroupId
2179 * Option group id.
2180 */
2181 public static function checkOptionGroup($optionGroupId) {
2182 $query = "
2183 SELECT count(*)
2184 FROM civicrm_custom_field
2185 WHERE option_group_id = {$optionGroupId}";
2186
2187 $count = CRM_Core_DAO::singleValueQuery($query);
2188
2189 if ($count < 2) {
2190 //delete the option group
2191 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2192 }
2193 }
2194
2195 /**
2196 * Get option group default.
2197 *
2198 * @param int $optionGroupId
2199 * @param string $htmlType
2200 *
2201 * @return null|string
2202 */
2203 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2204 $query = "
2205 SELECT default_value, html_type
2206 FROM civicrm_custom_field
2207 WHERE option_group_id = {$optionGroupId}
2208 AND default_value IS NOT NULL
2209 ORDER BY html_type";
2210
2211 $dao = CRM_Core_DAO::executeQuery($query);
2212 $defaultValue = NULL;
2213 $defaultHTMLType = NULL;
2214 while ($dao->fetch()) {
2215 if ($dao->html_type == $htmlType) {
2216 return $dao->default_value;
2217 }
2218 if ($defaultValue == NULL) {
2219 $defaultValue = $dao->default_value;
2220 $defaultHTMLType = $dao->html_type;
2221 }
2222 }
2223
2224 // some conversions are needed if either the old or new has a html type which has potential
2225 // multiple default values.
2226 if (($htmlType == 'CheckBox' || $htmlType == 'Multi-Select') &&
2227 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2228 ) {
2229 $defaultValue = CRM_Core_DAO::VALUE_SEPARATOR . $defaultValue . CRM_Core_DAO::VALUE_SEPARATOR;
2230 }
2231 elseif (($defaultHTMLType == 'CheckBox' || $defaultHTMLType == 'Multi-Select') &&
2232 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2233 ) {
2234 $defaultValue = substr($defaultValue, 1, -1);
2235 $values = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2236 substr($defaultValue, 1, -1)
2237 );
2238 $defaultValue = $values[0];
2239 }
2240
2241 return $defaultValue;
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 }