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