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