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