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