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