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