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