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