Merge pull request #16670 from demeritcowboy/audit-tpl-3
[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
cf346323 1070 return self::formatDisplayValue($value, $fieldInfo, $entityId);
3b66f502
CW
1071 }
1072
3b66f502
CW
1073 /**
1074 * Lower-level logic for rendering a custom field value
1075 *
1076 * @param string|array $value
1077 * @param array $field
080d719e 1078 * @param int|null $entityId
3b66f502 1079 *
51a3717f 1080 * @return string
3b66f502 1081 */
080d719e 1082 private static function formatDisplayValue($value, $field, $entityId = NULL) {
51a3717f 1083
3b66f502 1084 if (self::isSerialized($field) && !is_array($value)) {
74d79c61 1085 $value = CRM_Utils_Array::explodePadded($value);
3b66f502
CW
1086 }
1087 // CRM-12989 fix
6ebb4fa8
ML
1088 if ($field['html_type'] == 'CheckBox' && $value) {
1089 $value = CRM_Utils_Array::convertCheckboxFormatToArray($value);
3b66f502 1090 }
51a3717f
CW
1091
1092 $display = is_array($value) ? implode(', ', $value) : (string) $value;
1093
3b66f502
CW
1094 switch ($field['html_type']) {
1095
1096 case 'Select':
1097 case 'Autocomplete-Select':
1098 case 'Radio':
1099 case 'Select Country':
1100 case 'Select State/Province':
6a488035 1101 case 'CheckBox':
6a488035 1102 case 'Multi-Select':
3b66f502
CW
1103 case 'Multi-Select State/Province':
1104 case 'Multi-Select Country':
1105 if ($field['data_type'] == 'ContactReference' && $value) {
69b2206a
AS
1106 if (is_numeric($value)) {
1107 $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1108 }
1109 else {
1110 $display = $value;
1111 }
6a488035 1112 }
3b66f502 1113 elseif (is_array($value)) {
5f627bb5 1114 $v = [];
3b66f502 1115 foreach ($value as $key => $val) {
9c1bc317 1116 $v[] = $field['options'][$val] ?? NULL;
6a488035 1117 }
6a488035
TO
1118 $display = implode(', ', $v);
1119 }
3b66f502 1120 else {
51a3717f 1121 $display = CRM_Utils_Array::value($value, $field['options'], '');
3b66f502 1122 }
6a488035
TO
1123 break;
1124
1125 case 'Select Date':
51a3717f
CW
1126 $customFormat = NULL;
1127
74d79c61
CW
1128 // FIXME: Are there any legitimate reasons why $value would be an array?
1129 // Or should we throw an exception here if it is?
1130 $value = is_array($value) ? CRM_Utils_Array::first($value) : $value;
1131
ed0ca248 1132 $actualPHPFormats = CRM_Utils_Date::datePluginToPHPFormats();
9c1bc317 1133 $format = $field['date_format'] ?? NULL;
51a3717f
CW
1134
1135 if ($format) {
1136 if (array_key_exists($format, $actualPHPFormats)) {
1137 $customTimeFormat = (array) $actualPHPFormats[$format];
1138 switch (CRM_Utils_Array::value('time_format', $field)) {
1139 case 1:
1140 $customTimeFormat[] = 'g:iA';
1141 break;
1142
1143 case 2:
1144 $customTimeFormat[] = 'G:i';
1145 break;
1146
1147 default:
c65ec456
JP
1148 //If time is not selected remove time from value.
1149 $value = $value ? date('Y-m-d', strtotime($value)) : '';
51a3717f
CW
1150 }
1151 $customFormat = implode(" ", $customTimeFormat);
6a488035 1152 }
6a488035 1153 }
51a3717f 1154 $display = CRM_Utils_Date::processDate($value, NULL, FALSE, $customFormat);
6a488035
TO
1155 break;
1156
6a488035 1157 case 'File':
5f7e0d20 1158 // In the context of displaying a profile, show file/image
e34e6979 1159 if ($value) {
1160 if ($entityId) {
1470f70a
CW
1161 if (CRM_Utils_Rule::positiveInteger($value)) {
1162 $fileId = $value;
1163 }
1164 else {
1165 $fileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1166 }
1167 $url = self::getFileURL($entityId, $field['id'], $fileId);
e34e6979 1168 if ($url) {
1169 $display = $url['file_url'];
1170 }
1171 }
1172 else {
1173 // In other contexts show a paperclip icon
5a1bbef4 1174 if (CRM_Utils_Rule::integer($value)) {
1175 $icons = CRM_Core_BAO_File::paperIconAttachment('*', $value);
419b013b
D
1176
1177 $file_description = '';
1178 try {
1179 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1180 }
1181 catch (CiviCRM_API3_Exception $dontcare) {
1182 // don't care
1183 }
1184
1185 $display = "{$icons[$value]}{$file_description}";
5a1bbef4 1186 }
1187 else {
1188 //CRM-18396, if filename is passed instead
1189 $display = $value;
1190 }
5f7e0d20 1191 }
6a488035
TO
1192 }
1193 break;
1194
8472b684
CW
1195 case 'Link':
1196 $display = $display ? "<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1197 break;
1198
6a488035 1199 case 'TextArea':
51a3717f 1200 $display = nl2br($display);
6a488035 1201 break;
5d4ee51f 1202
1203 case 'Text':
1204 if ($field['data_type'] == 'Money' && isset($value)) {
aa965915 1205 // $value can also be an array(while using IN operator from search builder or api).
5d4ee51f 1206 foreach ((array) $value as $val) {
9a4f958b 1207 $disp[] = CRM_Utils_Money::format($val, NULL, NULL, TRUE);
5d4ee51f 1208 }
1209 $display = implode(', ', $disp);
1210 }
1211 break;
6a488035 1212 }
51a3717f 1213 return $display;
6a488035
TO
1214 }
1215
1216 /**
fe482240 1217 * Set default values for custom data used in profile.
6a488035 1218 *
6a0b768e
TO
1219 * @param int $customFieldId
1220 * Custom field id.
1221 * @param string $elementName
1222 * Custom field name.
1223 * @param array $defaults
1224 * Associated array of fields.
1225 * @param int $contactId
1226 * Contact id.
1227 * @param int $mode
1228 * Profile mode.
1229 * @param mixed $value
1230 * If passed - dont fetch value from db,.
6a488035 1231 * just format the given value
6a488035 1232 */
2da40d21 1233 public static function setProfileDefaults(
f9f40af3 1234 $customFieldId,
6a488035
TO
1235 $elementName,
1236 &$defaults,
1237 $contactId = NULL,
1238 $mode = NULL,
1239 $value = NULL
1240 ) {
1241 //get the type of custom field
1242 $customField = new CRM_Core_BAO_CustomField();
1243 $customField->id = $customFieldId;
1244 $customField->find(TRUE);
1245
1246 if (!$contactId) {
1247 if ($mode == CRM_Profile_Form::MODE_CREATE) {
1248 $value = $customField->default_value;
1249 }
1250 }
1251 else {
1252 if (!isset($value)) {
f9f40af3
TO
1253 $info = self::getTableColumnGroup($customFieldId);
1254 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
6a488035
TO
1255 $result = CRM_Core_DAO::executeQuery($query);
1256 if ($result->fetch()) {
1257 $value = $result->value;
1258 }
1259 }
1260
1261 if ($customField->data_type == 'Country') {
1262 if (!$value) {
1263 $config = CRM_Core_Config::singleton();
1264 if ($config->defaultContactCountry) {
d14f0a66 1265 $value = CRM_Core_BAO_Country::defaultContactCountry();
6a488035
TO
1266 }
1267 }
1268 }
1269 }
1270
1271 //set defaults if mode is registration
1272 if (!trim($value) &&
1273 ($value !== 0) &&
5f627bb5 1274 (!in_array($mode, [CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH]))
6a488035
TO
1275 ) {
1276 $value = $customField->default_value;
1277 }
1278
1279 if ($customField->data_type == 'Money' && isset($value)) {
1280 $value = number_format($value, 2);
1281 }
1282 switch ($customField->html_type) {
1283 case 'CheckBox':
6a488035
TO
1284 case 'Multi-Select':
1285 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
5f627bb5 1286 $defaults[$elementName] = [];
6a488035
TO
1287 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1288 substr($value, 1, -1)
1289 );
1290 foreach ($customOption as $val) {
1291 if (in_array($val['value'], $checkedValue)) {
1292 if ($customField->html_type == 'CheckBox') {
1293 $defaults[$elementName][$val['value']] = 1;
1294 }
6cc845ad 1295 elseif ($customField->html_type == 'Multi-Select') {
6a488035
TO
1296 $defaults[$elementName][$val['value']] = $val['value'];
1297 }
1298 }
1299 }
1300 break;
1301
6a488035
TO
1302 default:
1303 $defaults[$elementName] = $value;
1304 }
1305 }
1306
b5c2afd0 1307 /**
b60efd6a 1308 * Get file url.
b5c2afd0 1309 *
100fef9d
CW
1310 * @param int $contactID
1311 * @param int $cfID
1312 * @param int $fileID
b5c2afd0
EM
1313 * @param bool $absolute
1314 *
ad37ac8e 1315 * @param string $multiRecordWhereClause
1316 *
b5c2afd0
EM
1317 * @return array
1318 */
00be9182 1319 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
6a488035
TO
1320 if ($contactID) {
1321 if (!$fileID) {
5f627bb5
SL
1322 $params = ['id' => $cfID];
1323 $defaults = [];
6a488035
TO
1324 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1325 $columnName = $defaults['column_name'];
1326
1327 //table name of custom data
1328 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1329 $defaults['custom_group_id'],
1330 'table_name', 'id'
1331 );
1332
1333 //query to fetch id from civicrm_file
b42d84aa 1334 if ($multiRecordWhereClause) {
1335 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1336 }
1337 else {
1338 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1339 }
6a488035
TO
1340 $fileID = CRM_Core_DAO::singleValueQuery($query);
1341 }
1342
5f627bb5 1343 $result = [];
6a488035
TO
1344 if ($fileID) {
1345 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1346 $fileID,
1347 'mime_type',
1348 'id'
1349 );
1350 $result['file_id'] = $fileID;
1351
1352 if ($fileType == 'image/jpeg' ||
1353 $fileType == 'image/pjpeg' ||
1354 $fileType == 'image/gif' ||
1355 $fileType == 'image/x-png' ||
1356 $fileType == 'image/png'
1357 ) {
1358 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1359 $fileID,
1360 'entity_id',
c55199e1 1361 'file_id'
6a488035 1362 );
9bbc34f1 1363 list($path) = CRM_Core_BAO_File::path($fileID, $entityId);
efddd94f 1364 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileID);
6a488035 1365 $url = CRM_Utils_System::url('civicrm/file',
0ada9416 1366 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
6a488035
TO
1367 $absolute, NULL, TRUE, TRUE
1368 );
f3726153 1369 $result['file_url'] = CRM_Utils_File::getFileURL($path, $fileType, $url);
6a488035 1370 }
f3726153 1371 // for non image files
6a488035
TO
1372 else {
1373 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1374 $fileID,
1375 'uri'
1376 );
0ada9416 1377 $fileHash = CRM_Core_BAO_File::generateFileHash($contactID, $fileID);
6a488035 1378 $url = CRM_Utils_System::url('civicrm/file',
ff9aeadb 1379 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
6a488035
TO
1380 $absolute, NULL, TRUE, TRUE
1381 );
f3726153 1382 $result['file_url'] = CRM_Utils_File::getFileURL($uri, $fileType, $url);
6a488035
TO
1383 }
1384 }
1385 return $result;
1386 }
1387 }
1388
1389 /**
fe482240 1390 * Format custom fields before inserting.
6a488035 1391 *
6a0b768e
TO
1392 * @param int $customFieldId
1393 * Custom field id.
1394 * @param array $customFormatted
1395 * Formatted array.
bb06e9ed 1396 * @param mixed $value
6a0b768e
TO
1397 * Value of custom field.
1398 * @param string $customFieldExtend
1399 * Custom field extends.
1400 * @param int $customValueId
1401 * Custom option value id.
1402 * @param int $entityId
1403 * Entity id (contribution, membership...).
1404 * @param bool $inline
1405 * Consider inline custom groups only.
1406 * @param bool $checkPermission
1407 * If false, do not include permissioning clause.
1408 * @param bool $includeViewOnly
1409 * If true, fields marked 'View Only' are included. Required for APIv3.
6a488035 1410 *
a1a2a83d 1411 * @return array|NULL
a6c01b45 1412 * formatted custom field array
6a488035 1413 */
2da40d21 1414 public static function formatCustomField(
f9f40af3 1415 $customFieldId, &$customFormatted, $value,
6a488035
TO
1416 $customFieldExtend, $customValueId = NULL,
1417 $entityId = NULL,
1418 $inline = FALSE,
211353a8 1419 $checkPermission = TRUE,
f9f40af3 1420 $includeViewOnly = FALSE
6a488035
TO
1421 ) {
1422 //get the custom fields for the entity
1423 //subtype and basic type
1424 $customDataSubType = NULL;
e25c4389 1425 if ($customFieldExtend) {
6a488035
TO
1426 // This is the case when getFieldsForImport() requires fields
1427 // of subtype and its parent.CRM-5143
d9ef38cc 1428 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1429 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType::subTypes(), (array) $customFieldExtend);
1430 if (!empty($customDataSubType) && is_array($customDataSubType)) {
e25c4389 1431 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1432 if (is_array($customFieldExtend)) {
1433 $customFieldExtend = array_unique(array_values($customFieldExtend));
1434 }
d9ef38cc 1435 }
6a488035
TO
1436 }
1437
1438 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1439 FALSE,
1440 $inline,
1441 $customDataSubType,
1442 NULL,
1443 FALSE,
1444 FALSE,
1445 $checkPermission
1446 );
1447
1448 if (!array_key_exists($customFieldId, $customFields)) {
6c552737 1449 return NULL;
6a488035
TO
1450 }
1451
1452 // return if field is a 'code' field
211353a8 1453 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
a1a2a83d 1454 return NULL;
6a488035
TO
1455 }
1456
1457 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1458
6a488035
TO
1459 if (!$customValueId &&
1460 // we always create new entites for is_multiple unless specified
1461 !$customFields[$customFieldId]['is_multiple'] &&
1462 $entityId
1463 ) {
1464 $query = "
1465SELECT id
1466 FROM $tableName
1467 WHERE entity_id={$entityId}";
1468
1469 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1470 }
1471
1472 //fix checkbox, now check box always submits values
1473 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1474 if ($value) {
1475 // Note that only during merge this is not an array, and you can directly use value
1476 if (is_array($value)) {
5f627bb5 1477 $selectedValues = [];
6a488035
TO
1478 foreach ($value as $selId => $val) {
1479 if ($val) {
1480 $selectedValues[] = $selId;
1481 }
1482 }
1483 if (!empty($selectedValues)) {
1484 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
f9f40af3
TO
1485 $selectedValues
1486 ) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
1487 }
1488 else {
1489 $value = '';
1490 }
1491 }
1492 }
1493 }
1494
6cc845ad 1495 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select') {
6a488035 1496 if ($value) {
a20a1d89 1497 $value = CRM_Utils_Array::implodePadded($value);
6a488035
TO
1498 }
1499 else {
1500 $value = '';
1501 }
1502 }
1503
1504 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
6a488035
TO
1505 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1506 ) &&
1507 $customFields[$customFieldId]['data_type'] == 'String' &&
1508 !empty($customFields[$customFieldId]['text_length']) &&
1509 !empty($value)
1510 ) {
1511 // lets make sure that value is less than the length, else we'll
1512 // be losing some data, CRM-7481
1513 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1514 // need to do a few things here
1515
1516 // 1. lets find a new length
1517 $newLength = $customFields[$customFieldId]['text_length'];
1518 $minLength = strlen($value);
1519 while ($newLength < $minLength) {
1520 $newLength = $newLength * 2;
1521 }
1522
1523 // set the custom field meta data to have a length larger than value
1524 // alter the custom value table column to match this length
1525 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1526 }
1527 }
1528
1529 $date = NULL;
1530 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1531 if (!CRM_Utils_System::isNull($value)) {
1532 $format = $customFields[$customFieldId]['date_format'];
1533 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1534 }
1535 $value = $date;
1536 }
1537
1538 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1539 $customFields[$customFieldId]['data_type'] == 'Money'
1540 ) {
1541 if (!$value) {
1542 $value = 0;
1543 }
1544
1545 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1546 $value = CRM_Utils_Rule::cleanMoney($value);
1547 }
1548 }
1549
1550 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1551 $customFields[$customFieldId]['data_type'] == 'Country'
1552 ) &&
1553 empty($value)
1554 ) {
1555 // CRM-3415
1556 $value = 0;
1557 }
1558
e5077b06 1559 $fileID = NULL;
6a488035
TO
1560
1561 if ($customFields[$customFieldId]['data_type'] == 'File') {
1562 if (empty($value)) {
1563 return;
1564 }
1565
1566 $config = CRM_Core_Config::singleton();
1567
756b5b30 1568 // If we are already passing the file id as a value then retrieve and set the file data
1569 if (CRM_Utils_Rule::integer($value)) {
1570 $fileDAO = new CRM_Core_DAO_File();
1571 $fileDAO->id = $value;
1572 $fileDAO->find(TRUE);
07702f3e 1573 if ($fileDAO->N) {
756b5b30 1574 $fileID = $value;
1575 $fName = $fileDAO->uri;
1576 $mimeType = $fileDAO->mime_type;
1577 }
1578 }
33d245c8
CW
1579 else {
1580 $fName = $value['name'];
1581 $mimeType = $value['type'];
1582 }
756b5b30 1583
6a488035
TO
1584 $filename = pathinfo($fName, PATHINFO_BASENAME);
1585
756b5b30 1586 // rename this file to go into the secure directory only if
1587 // user has uploaded new file not existing verfied on the basis of $fileID
ecc6bd60 1588 if (empty($fileID) && !rename($fName, $config->customFileUploadDir . $filename)) {
6a488035 1589 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
6a488035
TO
1590 }
1591
ecc6bd60 1592 if ($customValueId && empty($fileID)) {
6a488035
TO
1593 $query = "
1594SELECT $columnName
1595 FROM $tableName
1596 WHERE id = %1";
5f627bb5 1597 $params = [1 => [$customValueId, 'Integer']];
e5077b06 1598 $fileID = CRM_Core_DAO::singleValueQuery($query, $params);
6a488035
TO
1599 }
1600
1601 $fileDAO = new CRM_Core_DAO_File();
1602
e5077b06
AM
1603 if ($fileID) {
1604 $fileDAO->id = $fileID;
6a488035
TO
1605 }
1606
1607 $fileDAO->uri = $filename;
1608 $fileDAO->mime_type = $mimeType;
c13ff164 1609 $fileDAO->upload_date = date('YmdHis');
6a488035 1610 $fileDAO->save();
e5077b06 1611 $fileID = $fileDAO->id;
6a488035
TO
1612 $value = $filename;
1613 }
1614
1615 if (!is_array($customFormatted)) {
5f627bb5 1616 $customFormatted = [];
6a488035
TO
1617 }
1618
1619 if (!array_key_exists($customFieldId, $customFormatted)) {
5f627bb5 1620 $customFormatted[$customFieldId] = [];
6a488035
TO
1621 }
1622
1623 $index = -1;
1624 if ($customValueId) {
1625 $index = $customValueId;
1626 }
1627
1628 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
5f627bb5 1629 $customFormatted[$customFieldId][$index] = [];
6a488035 1630 }
5f627bb5 1631 $customFormatted[$customFieldId][$index] = [
6a488035
TO
1632 'id' => $customValueId > 0 ? $customValueId : NULL,
1633 'value' => $value,
1634 'type' => $customFields[$customFieldId]['data_type'],
1635 'custom_field_id' => $customFieldId,
1636 'custom_group_id' => $groupID,
1637 'table_name' => $tableName,
1638 'column_name' => $columnName,
e5077b06 1639 'file_id' => $fileID,
6a488035 1640 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
5f627bb5 1641 ];
6a488035
TO
1642
1643 //we need to sort so that custom fields are created in the order of entry
1644 krsort($customFormatted[$customFieldId]);
1645 return $customFormatted;
1646 }
1647
b5c2afd0 1648 /**
b60efd6a
EM
1649 * Get default custom table schema.
1650 *
c490a46a 1651 * @param array $params
b5c2afd0
EM
1652 *
1653 * @return array
1654 */
b60efd6a 1655 public static function defaultCustomTableSchema($params) {
6a488035 1656 // add the id and extends_id
5f627bb5 1657 $table = [
6a488035
TO
1658 'name' => $params['name'],
1659 'is_multiple' => $params['is_multiple'],
1660 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
5f627bb5
SL
1661 'fields' => [
1662 [
6a488035
TO
1663 'name' => 'id',
1664 'type' => 'int unsigned',
1665 'primary' => TRUE,
1666 'required' => TRUE,
1667 'attributes' => 'AUTO_INCREMENT',
1668 'comment' => 'Default MySQL primary key',
5f627bb5
SL
1669 ],
1670 [
6a488035
TO
1671 'name' => 'entity_id',
1672 'type' => 'int unsigned',
1673 'required' => TRUE,
1674 'comment' => 'Table that this extends',
1675 'fk_table_name' => $params['extends_name'],
1676 'fk_field_name' => 'id',
1677 'fk_attributes' => 'ON DELETE CASCADE',
5f627bb5
SL
1678 ],
1679 ],
1680 ];
6a488035
TO
1681
1682 if (!$params['is_multiple']) {
5f627bb5
SL
1683 $table['indexes'] = [
1684 [
6a488035
TO
1685 'unique' => TRUE,
1686 'field_name_1' => 'entity_id',
5f627bb5
SL
1687 ],
1688 ];
6a488035
TO
1689 }
1690 return $table;
1691 }
1692
b5c2afd0 1693 /**
b60efd6a
EM
1694 * Create custom field.
1695 *
1696 * @param CRM_Core_DAO_CustomField $field
1697 * @param string $operation
b5c2afd0 1698 */
ead0c08f 1699 public static function createField($field, $operation) {
3111965c 1700 $sql = str_repeat(' ', 8);
e5ce15c3 1701 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id, 'table_name');
1702 $sql .= "ALTER TABLE " . $tableName;
1703 $sql .= self::getAlterFieldSQL($field, $operation);
3111965c 1704
1705 // CRM-7007: do not i18n-rewrite this query
1706 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1707
1708 $config = CRM_Core_Config::singleton();
1709 if ($config->logging) {
1710 // CRM-16717 not sure why this was originally limited to add.
1711 // For example custom tables can have field length changes - which need to flow through to logging.
1712 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
e5ce15c3 1713 if ($operation === 'add' || $operation === 'modify') {
3111965c 1714 $logging = new CRM_Logging_Schema();
e5ce15c3 1715 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name]]);
3111965c 1716 }
1717 }
1718
ead0c08f 1719 Civi::service('sql_triggers')->rebuild($tableName, TRUE);
3111965c 1720 }
1721
1722 /**
1723 * @param CRM_Core_DAO_CustomField $field
1724 * @param string $operation
3111965c 1725 *
1726 * @return bool
1727 */
e5ce15c3 1728 public static function getAlterFieldSQL($field, $operation) {
1729 $indexExist = $operation === 'add' ? FALSE : CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $field->id, 'is_searchable');
c914d4dd 1730 $params = self::prepareCreateParams($field, $operation);
e5ce15c3 1731 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1732 // a function only used by Custom Field creation...
3111965c 1733 $params['required'] = FALSE;
3111965c 1734 return CRM_Core_BAO_SchemaHandler::getFieldAlterSQL($params, $indexExist);
6a488035
TO
1735 }
1736
1737 /**
fe482240 1738 * Determine whether it would be safe to move a field.
6a488035 1739 *
6a0b768e
TO
1740 * @param int $fieldID
1741 * FK to civicrm_custom_field.
1742 * @param int $newGroupID
1743 * FK to civicrm_custom_group.
6a488035 1744 *
5c766a0b
TO
1745 * @return array
1746 * array(string) or TRUE
6a488035 1747 */
00be9182 1748 public static function _moveFieldValidate($fieldID, $newGroupID) {
5f627bb5 1749 $errors = [];
6a488035
TO
1750
1751 $field = new CRM_Core_DAO_CustomField();
1752 $field->id = $fieldID;
1753 if (!$field->find(TRUE)) {
1754 $errors['fieldID'] = 'Invalid ID for custom field';
1755 return $errors;
1756 }
1757
1758 $oldGroup = new CRM_Core_DAO_CustomGroup();
1759 $oldGroup->id = $field->custom_group_id;
1760 if (!$oldGroup->find(TRUE)) {
1761 $errors['fieldID'] = 'Invalid ID for old custom group';
1762 return $errors;
1763 }
1764
1765 $newGroup = new CRM_Core_DAO_CustomGroup();
1766 $newGroup->id = $newGroupID;
1767 if (!$newGroup->find(TRUE)) {
1768 $errors['newGroupID'] = 'Invalid ID for new custom group';
1769 return $errors;
1770 }
1771
1772 $query = "
1773SELECT b.id
1774FROM civicrm_custom_field a
1775INNER JOIN civicrm_custom_field b
1776WHERE a.id = %1
1777AND a.label = b.label
1778AND b.custom_group_id = %2
1779";
5f627bb5
SL
1780 $params = [
1781 1 => [$field->id, 'Integer'],
1782 2 => [$newGroup->id, 'Integer'],
1783 ];
6a488035
TO
1784 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1785 if ($count > 0) {
1786 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1787 }
1788
1789 $tableName = $oldGroup->table_name;
1790 $columnName = $field->column_name;
1791
1792 $query = "
1793SELECT count(*)
1794FROM $tableName
1795WHERE $columnName is not null
1796";
e03e1641 1797 $count = CRM_Core_DAO::singleValueQuery($query);
6a488035
TO
1798 if ($count > 0) {
1799 $query = "
1800SELECT extends
1801FROM civicrm_custom_group
1802WHERE id IN ( %1, %2 )
1803";
5f627bb5
SL
1804 $params = [
1805 1 => [$oldGroup->id, 'Integer'],
1806 2 => [$newGroup->id, 'Integer'],
1807 ];
6a488035
TO
1808
1809 $dao = CRM_Core_DAO::executeQuery($query, $params);
5f627bb5 1810 $extends = [];
6a488035
TO
1811 while ($dao->fetch()) {
1812 $extends[] = $dao->extends;
1813 }
1814 if ($extends[0] != $extends[1]) {
1815 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1816 }
1817 }
1818
1819 return empty($errors) ? TRUE : $errors;
1820 }
1821
1822 /**
b60efd6a 1823 * Move a custom data field from one group (table) to another.
6a488035 1824 *
6a0b768e
TO
1825 * @param int $fieldID
1826 * FK to civicrm_custom_field.
1827 * @param int $newGroupID
1828 * FK to civicrm_custom_group.
6a488035 1829 */
00be9182 1830 public static function moveField($fieldID, $newGroupID) {
6a488035
TO
1831 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
1832 if (TRUE !== $validation) {
1833 CRM_Core_Error::fatal(implode(' ', $validation));
1834 }
1835 $field = new CRM_Core_DAO_CustomField();
1836 $field->id = $fieldID;
1837 $field->find(TRUE);
1838
1839 $newGroup = new CRM_Core_DAO_CustomGroup();
1840 $newGroup->id = $newGroupID;
1841 $newGroup->find(TRUE);
1842
1843 $oldGroup = new CRM_Core_DAO_CustomGroup();
1844 $oldGroup->id = $field->custom_group_id;
1845 $oldGroup->find(TRUE);
1846
1847 $add = clone$field;
1848 $add->custom_group_id = $newGroup->id;
1849 self::createField($add, 'add');
1850
1851 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1852 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1853 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1854 ";
1855 CRM_Core_DAO::executeQuery($sql);
1856
1857 $del = clone$field;
1858 $del->custom_group_id = $oldGroup->id;
1859 self::createField($del, 'delete');
1860
1861 $add->save();
1862
1863 CRM_Utils_System::flushCache();
1864 }
1865
554a91f6 1866 /**
1867 * Create an option value for a custom field option group ID.
1868 *
1869 * @param array $params
1870 * @param string $value
1871 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1872 * @param string $optionName
1873 * @param string $dataType
1874 */
1875 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup $optionGroup, $optionName, $dataType) {
1876 if (strlen(trim($value))) {
1877 $optionValue = new CRM_Core_DAO_OptionValue();
1878 $optionValue->option_group_id = $optionGroup->id;
1879 $optionValue->label = $params['option_label'][$optionName];
1880 $optionValue->name = CRM_Utils_String::titleToVar($params['option_label'][$optionName]);
1881 switch ($dataType) {
1882 case 'Money':
1883 $optionValue->value = CRM_Utils_Rule::cleanMoney($value);
1884 break;
1885
1886 case 'Int':
1887 $optionValue->value = intval($value);
1888 break;
1889
1890 case 'Float':
1891 $optionValue->value = floatval($value);
1892 break;
1893
1894 default:
1895 $optionValue->value = trim($value);
1896 }
1897
1898 $optionValue->weight = $params['option_weight'][$optionName];
1899 $optionValue->is_active = CRM_Utils_Array::value($optionName, $params['option_status'], FALSE);
1900 $optionValue->save();
1901 }
1902 }
1903
4f166aec 1904 /**
1905 * Prepare for the create operation.
1906 *
1907 * Munge params, create the option values if needed.
1908 *
1909 * This could be called by a single create or a batchCreate.
1910 *
1911 * @param array $params
4f166aec 1912 *
1913 * @return array
1914 */
e43db21d 1915 protected static function prepareCreate($params) {
1916 $op = empty($params['id']) ? 'create' : 'edit';
4f166aec 1917 CRM_Utils_Hook::pre($op, 'CustomField', CRM_Utils_Array::value('id', $params), $params);
b5c280fc 1918 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
4f166aec 1919 if ($op === 'create') {
1920 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
1921 if (!isset($params['column_name'])) {
1922 // if add mode & column_name not present, calculate it.
1923 $params['column_name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 32));
1924 }
1925 if (!isset($params['name'])) {
1926 $params['name'] = CRM_Utils_String::munge($params['label'], '_', 64);
1927 }
1928 }
1929 else {
1930 $params['column_name'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1931 $params['id'],
1932 'column_name'
1933 );
1934 }
1935
1936 switch (CRM_Utils_Array::value('html_type', $params)) {
1937 case 'Select Date':
1938 if (empty($params['date_format'])) {
1939 $config = CRM_Core_Config::singleton();
1940 $params['date_format'] = $config->dateInputFormat;
1941 }
1942 break;
1943
1944 case 'CheckBox':
1945 case 'Multi-Select':
1946 if (isset($params['default_checkbox_option'])) {
1947 $tempArray = array_keys($params['default_checkbox_option']);
1948 $defaultArray = [];
1949 foreach ($tempArray as $k => $v) {
1950 if ($params['option_value'][$v]) {
1951 $defaultArray[] = $params['option_value'][$v];
1952 }
1953 }
1954
1955 if (!empty($defaultArray)) {
1956 // also add the separator before and after the value per new convention (CRM-1604)
1957 $params['default_value'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $defaultArray) . CRM_Core_DAO::VALUE_SEPARATOR;
1958 }
1959 }
1960 else {
1961 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
1962 ) {
1963 $params['default_value'] = $params['option_value'][$params['default_option']];
1964 }
1965 }
1966 break;
1967 }
1968
9c1bc317
CW
1969 $htmlType = $params['html_type'] ?? NULL;
1970 $dataType = $params['data_type'] ?? NULL;
4f166aec 1971 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1972
1973 // create any option group & values if required
1974 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)
1975 ) {
1976 //CRM-16659: if option_value then create an option group for this custom field.
1977 if ($params['option_type'] == 1 && (empty($params['option_group_id']) || !empty($params['option_value']))) {
1978 // first create an option group for this custom group
1979 $optionGroup = new CRM_Core_DAO_OptionGroup();
1980 $optionGroup->name = "{$params['column_name']}_" . date('YmdHis');
1981 $optionGroup->title = $params['label'];
1982 $optionGroup->is_active = 1;
1983 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1984 $optionGroup->is_reserved = 0;
1985 $optionGroup->data_type = $dataType;
1986 $optionGroup->save();
1987 $params['option_group_id'] = $optionGroup->id;
1988 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1989 foreach ($params['option_value'] as $k => $v) {
1990 self::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1991 }
1992 }
1993 }
1994 }
1995
1996 // check for orphan option groups
1997 if (!empty($params['option_group_id'])) {
1998 if (!empty($params['id'])) {
1999 self::fixOptionGroups($params['id'], $params['option_group_id']);
2000 }
2001
2002 // if we do not have a default value
2003 // retrieve it from one of the other custom fields which use this option group
2004 if (empty($params['default_value'])) {
2005 //don't insert only value separator as default value, CRM-4579
2006 $defaultValue = self::getOptionGroupDefault($params['option_group_id'],
2007 $htmlType
2008 );
2009
2010 if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR,
2011 $defaultValue
2012 ))
2013 ) {
2014 $params['default_value'] = $defaultValue;
2015 }
2016 }
2017 }
2018
2019 // since we need to save option group id :)
2020 if (!isset($params['attributes']) && strtolower($htmlType) == 'textarea') {
2021 $params['attributes'] = 'rows=4, cols=60';
2022 }
2023 return $params;
2024 }
2025
f45a42ba 2026 /**
2027 * Create database entry for custom field and related option groups.
2028 *
2029 * @param array $params
2030 *
2031 * @return CRM_Core_DAO_CustomField
2032 */
2033 protected static function createCustomFieldRecord($params) {
2034 $transaction = new CRM_Core_Transaction();
2035 $params = self::prepareCreate($params);
2036
2037 $customField = new CRM_Core_DAO_CustomField();
2038 $customField->copyValues($params);
2039 $customField->save();
2040
2041 //create/drop the index when we toggle the is_searchable flag
2042 $op = empty($params['id']) ? 'add' : 'modify';
2043 if ($op !== 'modify') {
2044 if ($params['is_append_field_id_to_column_name']) {
2045 $params['column_name'] .= "_{$customField->id}";
2046 }
2047 $customField->column_name = $params['column_name'];
2048 $customField->save();
2049 }
2050
2051 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2052 $transaction->commit();
2053
2054 // make sure all values are present in the object for further processing
2055 $customField->find(TRUE);
2056 return $customField;
2057 }
2058
1600a9c0 2059 /**
2060 * Move custom data from one contact to another.
2061 *
2062 * This is currently the start of a refactoring. The theory is each
2063 * entity could have a 'move' function with a DAO default one to fall back on.
2064 *
2065 * At the moment this only does a small part of the process - ie deleting a file field that
2066 * is about to be overwritten. However, the goal is the whole process around the move for
2067 * custom data should be in here.
2068 *
2069 * This is currently called by the merge class but it makes sense that api could
2070 * expose move actions as moving (e.g) contributions feels like a common
2071 * ask that should be handled by the form layer.
2072 *
2073 * @param int $oldContactID
2074 * @param int $newContactID
2075 * @param int[] $fieldIDs
2076 * Optional list field ids to move.
2077 *
2078 * @throws \CiviCRM_API3_Exception
2079 * @throws \Exception
2080 */
2081 public function move($oldContactID, $newContactID, $fieldIDs) {
2082 if (empty($fieldIDs)) {
2083 return;
2084 }
2085 $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'];
2086 $return = [];
2087 foreach ($fieldIDs as $fieldID) {
2088 $return[] = 'custom_' . $fieldID;
2089 }
2090 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2091 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2092
2093 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2094 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2095 $fieldTypesNotHandledInMergeAttempt = ['File'];
2096 foreach ($fields as $field) {
2097 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2098 if ($field['data_type'] === 'File' && !$isMultiple) {
2099 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2100 CRM_Core_BAO_File::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2101 }
2102 if (!empty($oldContact['custom_' . $field['id']])) {
2103 CRM_Core_DAO::executeQuery("
2104 UPDATE civicrm_entity_file
2105 SET entity_id = $newContactID
2106 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2107 );
2108 }
2109 }
2110 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2111 CRM_Core_DAO::executeQuery(
2112 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2113 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2114 ON DUPLICATE KEY UPDATE
2115 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2116 ");
2117 }
2118 }
2119 }
2120
6a488035 2121 /**
fe482240 2122 * Get the database table name and column name for a custom field.
6a488035 2123 *
6a0b768e
TO
2124 * @param int $fieldID
2125 * The fieldID of the custom field.
2126 * @param bool $force
2127 * Force the sql to be run again (primarily used for tests).
6a488035 2128 *
a6c01b45
CW
2129 * @return array
2130 * fatal is fieldID does not exists, else array of tableName, columnName
1600a9c0 2131 * @throws \Exception
6a488035 2132 */
00be9182 2133 public static function getTableColumnGroup($fieldID, $force = FALSE) {
f9f40af3
TO
2134 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2135 $cache = CRM_Utils_Cache::singleton();
6a488035
TO
2136 $fieldValues = $cache->get($cacheKey);
2137 if (empty($fieldValues) || $force) {
2138 $query = "
2139SELECT cg.table_name, cf.column_name, cg.id
2140FROM civicrm_custom_group cg,
2141 civicrm_custom_field cf
2142WHERE cf.custom_group_id = cg.id
2143AND cf.id = %1";
5f627bb5 2144 $params = [1 => [$fieldID, 'Integer']];
6a488035
TO
2145 $dao = CRM_Core_DAO::executeQuery($query, $params);
2146
2147 if (!$dao->fetch()) {
2148 CRM_Core_Error::fatal();
2149 }
5f627bb5 2150 $fieldValues = [$dao->table_name, $dao->column_name, $dao->id];
6a488035
TO
2151 $cache->set($cacheKey, $fieldValues);
2152 }
2153 return $fieldValues;
2154 }
2155
2156 /**
fe482240 2157 * Get custom option groups.
6a488035 2158 *
c0fce6be
MW
2159 * @deprecated Use the API OptionGroup.get
2160 *
6a0b768e 2161 * @param array $includeFieldIds
b60efd6a 2162 * Ids of custom fields for which option groups must be included.
6a488035
TO
2163 *
2164 * Currently this is required in the cases where option groups are to be included
2165 * for inactive fields : CRM-5369
2166 *
72b3a70c 2167 * @return mixed
6a488035 2168 */
b60efd6a 2169 public static function customOptionGroup($includeFieldIds = NULL) {
6a488035
TO
2170 static $customOptionGroup = NULL;
2171
2172 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
2173 if ($cacheKey == 'force') {
2174 $customOptionGroup[$cacheKey] = NULL;
2175 }
2176
a7488080 2177 if (empty($customOptionGroup[$cacheKey])) {
6a488035
TO
2178 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2179
2180 //support for single as well as array format.
2181 if (!empty($includeFieldIds)) {
2182 if (is_array($includeFieldIds)) {
2183 $includeFieldIds = implode(',', $includeFieldIds);
2184 }
2185 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2186 }
2187
2188 $query = "
2189 SELECT g.id, g.title
2190 FROM civicrm_option_group g
2191INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2192 WHERE {$whereClause}";
2193
2194 $dao = CRM_Core_DAO::executeQuery($query);
2195 while ($dao->fetch()) {
2196 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
2197 }
2198 }
2199
2200 return $customOptionGroup[$cacheKey];
2201 }
2202
58c232cb 2203 /**
2204 * Get defaults for new entity.
2205 *
2206 * @return array
2207 */
2208 public static function getDefaults() {
2209 return [
2210 'is_required' => FALSE,
2211 'is_searchable' => FALSE,
2212 'in_selector' => FALSE,
2213 'is_search_range' => FALSE,
2214 //CRM-15792 - Custom field gets disabled if is_active not set
2215 // this would ideally be a mysql default.
2216 'is_active' => TRUE,
2217 'is_view' => FALSE,
2218 ];
2219 }
2220
6a488035 2221 /**
fe482240 2222 * Fix orphan groups.
6a488035 2223 *
6a0b768e
TO
2224 * @param int $customFieldId
2225 * Custom field id.
2226 * @param int $optionGroupId
2227 * Option group id.
6a488035 2228 */
00be9182 2229 public static function fixOptionGroups($customFieldId, $optionGroupId) {
6a488035
TO
2230 // check if option group belongs to any custom Field else delete
2231 // get the current option group
2232 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2233 $customFieldId,
2234 'option_group_id'
2235 );
2236 // get the updated option group
2237 // if both are same return
aa4143bb 2238 if (!$currentOptionGroupId || $currentOptionGroupId == $optionGroupId) {
6a488035
TO
2239 return;
2240 }
2241
2242 // check if option group is related to any other field
2243 self::checkOptionGroup($currentOptionGroupId);
2244 }
2245
2246 /**
b60efd6a 2247 * Check if option group is related to more than one custom field.
6a488035 2248 *
6a0b768e
TO
2249 * @param int $optionGroupId
2250 * Option group id.
6a488035 2251 */
00be9182 2252 public static function checkOptionGroup($optionGroupId) {
6a488035
TO
2253 $query = "
2254SELECT count(*)
2255FROM civicrm_custom_field
2256WHERE option_group_id = {$optionGroupId}";
2257
2258 $count = CRM_Core_DAO::singleValueQuery($query);
2259
2260 if ($count < 2) {
2261 //delete the option group
2262 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2263 }
2264 }
2265
b5c2afd0 2266 /**
b60efd6a
EM
2267 * Get option group default.
2268 *
100fef9d 2269 * @param int $optionGroupId
b60efd6a 2270 * @param string $htmlType
b5c2afd0
EM
2271 *
2272 * @return null|string
2273 */
00be9182 2274 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
6a488035
TO
2275 $query = "
2276SELECT default_value, html_type
2277FROM civicrm_custom_field
2278WHERE option_group_id = {$optionGroupId}
2279AND default_value IS NOT NULL
2280ORDER BY html_type";
2281
f9f40af3
TO
2282 $dao = CRM_Core_DAO::executeQuery($query);
2283 $defaultValue = NULL;
6a488035
TO
2284 $defaultHTMLType = NULL;
2285 while ($dao->fetch()) {
2286 if ($dao->html_type == $htmlType) {
2287 return $dao->default_value;
2288 }
2289 if ($defaultValue == NULL) {
2290 $defaultValue = $dao->default_value;
2291 $defaultHTMLType = $dao->html_type;
2292 }
2293 }
2294
2295 // some conversions are needed if either the old or new has a html type which has potential
2296 // multiple default values.
2297 if (($htmlType == 'CheckBox' || $htmlType == 'Multi-Select') &&
2298 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2299 ) {
2300 $defaultValue = CRM_Core_DAO::VALUE_SEPARATOR . $defaultValue . CRM_Core_DAO::VALUE_SEPARATOR;
2301 }
2302 elseif (($defaultHTMLType == 'CheckBox' || $defaultHTMLType == 'Multi-Select') &&
2303 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2304 ) {
2305 $defaultValue = substr($defaultValue, 1, -1);
2306 $values = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2307 substr($defaultValue, 1, -1)
2308 );
2309 $defaultValue = $values[0];
2310 }
2311
2312 return $defaultValue;
2313 }
2314
b5c2afd0 2315 /**
b60efd6a
EM
2316 * Post process function.
2317 *
c490a46a 2318 * @param array $params
100fef9d 2319 * @param int $entityID
b60efd6a 2320 * @param string $customFieldExtends
b5c2afd0 2321 * @param bool $inline
e9ff5391 2322 * @param bool $checkPermissions
b5c2afd0
EM
2323 *
2324 * @return array
2325 */
2da40d21 2326 public static function postProcess(
f9f40af3 2327 &$params,
6a488035
TO
2328 $entityID,
2329 $customFieldExtends,
e9ff5391 2330 $inline = FALSE,
2331 $checkPermissions = TRUE
6a488035 2332 ) {
5f627bb5 2333 $customData = [];
6a488035
TO
2334
2335 foreach ($params as $key => $value) {
2336 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE)) {
2337
2338 // for autocomplete transfer hidden value instead of label
2339 if ($params[$key] && isset($params[$key . '_id'])) {
2340 $value = $params[$key . '_id'];
2341 }
2342
2343 // we need to append time with date
2344 if ($params[$key] && isset($params[$key . '_time'])) {
2345 $value .= ' ' . $params[$key . '_time'];
2346 }
2347
2348 CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0],
2349 $customData,
2350 $value,
2351 $customFieldExtends,
2352 $customFieldInfo[1],
2353 $entityID,
e9ff5391 2354 $inline,
2355 $checkPermissions
6a488035
TO
2356 );
2357 }
2358 }
2359 return $customData;
2360 }
2361
2921fb78 2362 /**
b906accb 2363 * Get custom field ID from field/group name/title.
2921fb78 2364 *
b906accb 2365 * @param string $fieldName Field name or label
30b6e002 2366 * @param string|null $groupName (Optional) Group name or label
b906accb 2367 * @param bool $fullString Whether to return "custom_123" or "123"
b60efd6a 2368 *
b906accb
MW
2369 * @return string|int|null
2370 * @throws \CiviCRM_API3_Exception
b5c2afd0 2371 */
30b6e002
PF
2372 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2373 $cacheKey = $groupName . '.' . $fieldName;
2374 if (!isset(Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
b906accb
MW
2375 $customFieldParams = [
2376 'name' => $fieldName,
2377 'label' => $fieldName,
2378 'options' => ['or' => [["name", "label"]]],
2379 ];
2380
30b6e002
PF
2381 if ($groupName) {
2382 $customFieldParams['custom_group_id.name'] = $groupName;
2383 $customFieldParams['custom_group_id.title'] = $groupName;
b906accb
MW
2384 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2385 }
6a488035 2386
b906accb
MW
2387 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2388
2389 if (empty($field['id'])) {
30b6e002
PF
2390 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2391 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
b906accb
MW
2392 }
2393 else {
30b6e002
PF
2394 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2395 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
b906accb 2396 }
6a488035 2397 }
b906accb
MW
2398
2399 if ($fullString) {
30b6e002 2400 return Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
6a488035 2401 }
30b6e002 2402 return Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
6a488035
TO
2403 }
2404
2405 /**
2406 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
67f947ac
EM
2407 *
2408 * @param array $ids
2409 *
2410 * @return array
6a488035 2411 */
00be9182 2412 public static function getNameFromID($ids) {
6a488035
TO
2413 if (is_array($ids)) {
2414 $ids = implode(',', $ids);
2415 }
2416 $sql = "
2417SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2418FROM civicrm_custom_field f
2419INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2420WHERE f.id IN ($ids)";
2421
6a488035 2422 $dao = CRM_Core_DAO::executeQuery($sql);
5f627bb5 2423 $result = [];
6a488035 2424 while ($dao->fetch()) {
5f627bb5 2425 $result[$dao->id] = [
6a488035
TO
2426 'field_name' => $dao->field_name,
2427 'field_label' => $dao->field_label,
2428 'group_name' => $dao->group_name,
2429 'group_title' => $dao->group_title,
5f627bb5 2430 ];
6a488035
TO
2431 }
2432 return $result;
2433 }
2434
2435 /**
2436 * Validate custom data.
2437 *
6a0b768e
TO
2438 * @param array $params
2439 * Custom data submitted.
16b10e64 2440 * ie array( 'custom_1' => 'validate me' );
6a488035 2441 *
a6c01b45
CW
2442 * @return array
2443 * validation errors.
6a488035 2444 */
00be9182 2445 public static function validateCustomData($params) {
5f627bb5 2446 $errors = [];
6a488035
TO
2447 if (!is_array($params) || empty($params)) {
2448 return $errors;
2449 }
2450
6a488035 2451 //pick up profile fields.
5f627bb5 2452 $profileFields = [];
9c1bc317 2453 $ufGroupId = $params['ufGroupId'] ?? NULL;
6a488035
TO
2454 if ($ufGroupId) {
2455 $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId,
2456 FALSE,
2457 CRM_Core_Action::VIEW
2458 );
2459 }
2460
2461 //lets start w/ params.
2462 foreach ($params as $key => $value) {
2463 $customFieldID = self::getKeyID($key);
2464 if (!$customFieldID) {
2465 continue;
2466 }
2467
2468 //load the structural info for given field.
2469 $field = new CRM_Core_DAO_CustomField();
2470 $field->id = $customFieldID;
2471 if (!$field->find(TRUE)) {
2472 continue;
2473 }
2474 $dataType = $field->data_type;
2475
5f627bb5 2476 $profileField = CRM_Utils_Array::value($key, $profileFields, []);
9c1bc317
CW
2477 $fieldTitle = $profileField['title'] ?? NULL;
2478 $isRequired = $profileField['is_required'] ?? NULL;
6a488035
TO
2479 if (!$fieldTitle) {
2480 $fieldTitle = $field->label;
2481 }
2482
2483 //no need to validate.
2484 if (CRM_Utils_System::isNull($value) && !$isRequired) {
2485 continue;
2486 }
2487
2488 //lets validate first for required field.
2489 if ($isRequired && CRM_Utils_System::isNull($value)) {
5f627bb5 2490 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
6a488035
TO
2491 continue;
2492 }
2493
2494 //now time to take care of custom field form rules.
2495 $ruleName = $errorMsg = NULL;
2496 switch ($dataType) {
2497 case 'Int':
2498 $ruleName = 'integer';
2499 $errorMsg = ts('%1 must be an integer (whole number).',
2500 array(1 => $fieldTitle)
2501 );
2502 break;
2503
2504 case 'Money':
2505 $ruleName = 'money';
2506 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2507 array(1 => $fieldTitle)
2508 );
2509 break;
2510
2511 case 'Float':
2512 $ruleName = 'numeric';
2513 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2514 array(1 => $fieldTitle)
2515 );
2516 break;
2517
2518 case 'Link':
2519 $ruleName = 'wikiURL';
2520 $errorMsg = ts('%1 must be valid Website.',
2521 array(1 => $fieldTitle)
2522 );
2523 break;
2524 }
2525
2526 if ($ruleName && !CRM_Utils_System::isNull($value)) {
2527 $valid = FALSE;
2528 $funName = "CRM_Utils_Rule::{$ruleName}";
2529 if (is_callable($funName)) {
2530 $valid = call_user_func($funName, $value);
2531 }
2532 if (!$valid) {
2533 $errors[$key] = $errorMsg;
2534 }
2535 }
2536 }
2537
2538 return $errors;
2539 }
2540
ffd93213 2541 /**
b60efd6a
EM
2542 * Is this field a multi record field.
2543 *
100fef9d 2544 * @param int $customId
ffd93213
EM
2545 *
2546 * @return bool
2547 */
00be9182 2548 public static function isMultiRecordField($customId) {
6a488035
TO
2549 $isMultipleWithGid = FALSE;
2550 if (!is_numeric($customId)) {
2551 $customId = self::getKeyID($customId);
2552 }
2553 if (is_numeric($customId)) {
2554 $sql = "SELECT cg.id cgId
2555 FROM civicrm_custom_group cg
2556 INNER JOIN civicrm_custom_field cf
2557 ON cg.id = cf.custom_group_id
2558WHERE cf.id = %1 AND cg.is_multiple = 1";
5f627bb5 2559 $params[1] = [$customId, 'Integer'];
6a488035
TO
2560 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2561 if ($dao->fetch()) {
2562 if ($dao->cgId) {
2563 $isMultipleWithGid = $dao->cgId;
2564 }
2565 }
2566 }
2567
2568 return $isMultipleWithGid;
2569 }
3130209f 2570
1f8ac3d2
CW
2571 /**
2572 * Does this field type have any select options?
2573 *
2574 * @param array $field
2575 *
2576 * @return bool
2577 */
2578 public static function hasOptions($field) {
2579 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2580 $field = (array) $field;
2581 // This will include boolean fields with Yes/No options.
2582 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2583 return TRUE;
2584 }
2585 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2586 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2587 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2588 return FALSE;
2589 }
2590 if (strpos($field['html_type'], 'Select') !== FALSE) {
2591 return TRUE;
2592 }
2593 return !empty($field['option_group_id']);
2594 }
2595
3130209f
CW
2596 /**
2597 * Does this field store a serialized string?
b60efd6a 2598 *
3766bd36 2599 * @param array|object $field
b60efd6a 2600 *
3130209f
CW
2601 * @return bool
2602 */
00be9182 2603 public static function isSerialized($field) {
3130209f 2604 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
3766bd36 2605 $html_type = is_object($field) ? $field->html_type : $field['html_type'];
3130209f 2606 // 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 2607 return ($html_type === 'CheckBox' || strpos($html_type, 'Multi') !== FALSE);
3130209f 2608 }
96025800 2609
01057d41
CW
2610 /**
2611 * Get api entity for this field
2612 *
2613 * @return string
2614 */
2615 public function getEntity() {
2616 $entity = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id, 'extends');
5f627bb5 2617 return in_array($entity, ['Individual', 'Household', 'Organization']) ? 'Contact' : $entity;
01057d41
CW
2618 }
2619
14f42e31 2620 /**
3b66f502 2621 * Set pseudoconstant properties for field metadata.
b60efd6a 2622 *
14f42e31
CW
2623 * @param array $field
2624 * @param string|null $optionGroupName
2625 */
2626 private static function getOptionsForField(&$field, $optionGroupName) {
2627 if ($optionGroupName) {
5f627bb5 2628 $field['pseudoconstant'] = [
14f42e31
CW
2629 'optionGroupName' => $optionGroupName,
2630 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
5f627bb5 2631 ];
14f42e31
CW
2632 }
2633 elseif ($field['data_type'] == 'Boolean') {
5f627bb5 2634 $field['pseudoconstant'] = [
14f42e31 2635 'callback' => 'CRM_Core_SelectValues::boolean',
5f627bb5 2636 ];
14f42e31
CW
2637 }
2638 elseif ($field['data_type'] == 'Country') {
5f627bb5 2639 $field['pseudoconstant'] = [
14f42e31
CW
2640 'table' => 'civicrm_country',
2641 'keyColumn' => 'id',
2642 'labelColumn' => 'name',
2643 'nameColumn' => 'iso_code',
5f627bb5 2644 ];
14f42e31
CW
2645 }
2646 elseif ($field['data_type'] == 'StateProvince') {
5f627bb5 2647 $field['pseudoconstant'] = [
14f42e31
CW
2648 'table' => 'civicrm_state_province',
2649 'keyColumn' => 'id',
2650 'labelColumn' => 'name',
5f627bb5 2651 ];
14f42e31
CW
2652 }
2653 }
2654
c914d4dd 2655 /**
2656 * @param CRM_Core_DAO_CustomField $field
2657 * @param 'add|modify' $operation
2658 *
2659 * @return array
2660 */
2661 protected static function prepareCreateParams($field, $operation) {
2662 $tableName = CRM_Core_DAO::getFieldValue(
2663 'CRM_Core_DAO_CustomGroup',
2664 $field->custom_group_id,
2665 'table_name'
2666 );
2667
2668 $params = [
2669 'table_name' => $tableName,
2670 'operation' => $operation,
2671 'name' => $field->column_name,
2672 'type' => CRM_Core_BAO_CustomValueTable::fieldToSQLType(
2673 $field->data_type,
2674 $field->text_length
2675 ),
2676 'required' => $field->is_required,
2677 'searchable' => $field->is_searchable,
2678 ];
2679
2680 if ($operation == 'delete') {
2681 $fkName = "{$tableName}_{$field->column_name}";
2682 if (strlen($fkName) >= 48) {
2683 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2684 }
2685 $params['fkName'] = $fkName;
2686 }
2687 if ($field->data_type == 'Country' && $field->html_type == 'Select Country') {
2688 $params['fk_table_name'] = 'civicrm_country';
2689 $params['fk_field_name'] = 'id';
2690 $params['fk_attributes'] = 'ON DELETE SET NULL';
2691 }
2692 elseif ($field->data_type == 'Country' && $field->html_type == 'Multi-Select Country') {
2693 $params['type'] = 'varchar(255)';
2694 }
2695 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Select State/Province') {
2696 $params['fk_table_name'] = 'civicrm_state_province';
2697 $params['fk_field_name'] = 'id';
2698 $params['fk_attributes'] = 'ON DELETE SET NULL';
2699 }
2700 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Multi-Select State/Province') {
2701 $params['type'] = 'varchar(255)';
2702 }
2703 elseif ($field->data_type == 'File') {
2704 $params['fk_table_name'] = 'civicrm_file';
2705 $params['fk_field_name'] = 'id';
2706 $params['fk_attributes'] = 'ON DELETE SET NULL';
2707 }
2708 elseif ($field->data_type == 'ContactReference') {
2709 $params['fk_table_name'] = 'civicrm_contact';
2710 $params['fk_field_name'] = 'id';
2711 $params['fk_attributes'] = 'ON DELETE SET NULL';
2712 }
2713 if (isset($field->default_value)) {
2714 $params['default'] = "'{$field->default_value}'";
2715 }
2716 return $params;
2717 }
2718
6a488035 2719}