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