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