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