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