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