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