Merge pull request #17067 from colemanw/importSubmit
[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 * 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 if (self::isSerialized($customField)) {
1237 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
1238 $defaults[$elementName] = [];
1239 $checkedValue = CRM_Utils_Array::explodePadded($value);
1240 foreach ($customOption as $val) {
1241 if (in_array($val['value'], $checkedValue)) {
1242 if ($customField->html_type == 'CheckBox') {
1243 $defaults[$elementName][$val['value']] = 1;
1244 }
1245 else {
1246 $defaults[$elementName][$val['value']] = $val['value'];
1247 }
1248 }
1249 }
1250 }
1251 else {
1252 $defaults[$elementName] = $value;
1253 }
1254 }
1255
1256 /**
1257 * Get file url.
1258 *
1259 * @param int $contactID
1260 * @param int $cfID
1261 * @param int $fileID
1262 * @param bool $absolute
1263 *
1264 * @param string $multiRecordWhereClause
1265 *
1266 * @return array
1267 */
1268 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1269 if ($contactID) {
1270 if (!$fileID) {
1271 $params = ['id' => $cfID];
1272 $defaults = [];
1273 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1274 $columnName = $defaults['column_name'];
1275
1276 //table name of custom data
1277 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1278 $defaults['custom_group_id'],
1279 'table_name', 'id'
1280 );
1281
1282 //query to fetch id from civicrm_file
1283 if ($multiRecordWhereClause) {
1284 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1285 }
1286 else {
1287 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1288 }
1289 $fileID = CRM_Core_DAO::singleValueQuery($query);
1290 }
1291
1292 $result = [];
1293 if ($fileID) {
1294 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1295 $fileID,
1296 'mime_type',
1297 'id'
1298 );
1299 $result['file_id'] = $fileID;
1300
1301 if ($fileType == 'image/jpeg' ||
1302 $fileType == 'image/pjpeg' ||
1303 $fileType == 'image/gif' ||
1304 $fileType == 'image/x-png' ||
1305 $fileType == 'image/png'
1306 ) {
1307 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1308 $fileID,
1309 'entity_id',
1310 'file_id'
1311 );
1312 list($path) = CRM_Core_BAO_File::path($fileID, $entityId);
1313 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileID);
1314 $url = CRM_Utils_System::url('civicrm/file',
1315 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1316 $absolute, NULL, TRUE, TRUE
1317 );
1318 $result['file_url'] = CRM_Utils_File::getFileURL($path, $fileType, $url);
1319 }
1320 // for non image files
1321 else {
1322 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1323 $fileID,
1324 'uri'
1325 );
1326 $fileHash = CRM_Core_BAO_File::generateFileHash($contactID, $fileID);
1327 $url = CRM_Utils_System::url('civicrm/file',
1328 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1329 $absolute, NULL, TRUE, TRUE
1330 );
1331 $result['file_url'] = CRM_Utils_File::getFileURL($uri, $fileType, $url);
1332 }
1333 }
1334 return $result;
1335 }
1336 }
1337
1338 /**
1339 * Format custom fields before inserting.
1340 *
1341 * @param int $customFieldId
1342 * Custom field id.
1343 * @param array $customFormatted
1344 * Formatted array.
1345 * @param mixed $value
1346 * Value of custom field.
1347 * @param string $customFieldExtend
1348 * Custom field extends.
1349 * @param int $customValueId
1350 * Custom option value id.
1351 * @param int $entityId
1352 * Entity id (contribution, membership...).
1353 * @param bool $inline
1354 * Consider inline custom groups only.
1355 * @param bool $checkPermission
1356 * If false, do not include permissioning clause.
1357 * @param bool $includeViewOnly
1358 * If true, fields marked 'View Only' are included. Required for APIv3.
1359 *
1360 * @return array|NULL
1361 * formatted custom field array
1362 */
1363 public static function formatCustomField(
1364 $customFieldId, &$customFormatted, $value,
1365 $customFieldExtend, $customValueId = NULL,
1366 $entityId = NULL,
1367 $inline = FALSE,
1368 $checkPermission = TRUE,
1369 $includeViewOnly = FALSE
1370 ) {
1371 //get the custom fields for the entity
1372 //subtype and basic type
1373 $customDataSubType = NULL;
1374 if ($customFieldExtend) {
1375 // This is the case when getFieldsForImport() requires fields
1376 // of subtype and its parent.CRM-5143
1377 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1378 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType::subTypes(), (array) $customFieldExtend);
1379 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1380 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1381 if (is_array($customFieldExtend)) {
1382 $customFieldExtend = array_unique(array_values($customFieldExtend));
1383 }
1384 }
1385 }
1386
1387 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1388 FALSE,
1389 $inline,
1390 $customDataSubType,
1391 NULL,
1392 FALSE,
1393 FALSE,
1394 $checkPermission
1395 );
1396
1397 if (!array_key_exists($customFieldId, $customFields)) {
1398 return NULL;
1399 }
1400
1401 // return if field is a 'code' field
1402 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1403 return NULL;
1404 }
1405
1406 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1407
1408 if (!$customValueId &&
1409 // we always create new entites for is_multiple unless specified
1410 !$customFields[$customFieldId]['is_multiple'] &&
1411 $entityId
1412 ) {
1413 $query = "
1414 SELECT id
1415 FROM $tableName
1416 WHERE entity_id={$entityId}";
1417
1418 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1419 }
1420
1421 //fix checkbox, now check box always submits values
1422 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1423 if ($value) {
1424 // Note that only during merge this is not an array, and you can directly use value
1425 if (is_array($value)) {
1426 $selectedValues = [];
1427 foreach ($value as $selId => $val) {
1428 if ($val) {
1429 $selectedValues[] = $selId;
1430 }
1431 }
1432 if (!empty($selectedValues)) {
1433 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1434 $selectedValues
1435 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1436 }
1437 else {
1438 $value = '';
1439 }
1440 }
1441 }
1442 }
1443 elseif (self::isSerialized($customFields[$customFieldId])) {
1444 $value = $value ? CRM_Utils_Array::implodePadded($value) : '';
1445 }
1446
1447 if (self::isSerialized($customFields[$customFieldId]) &&
1448 $customFields[$customFieldId]['data_type'] == 'String' &&
1449 !empty($customFields[$customFieldId]['text_length']) &&
1450 !empty($value)
1451 ) {
1452 // lets make sure that value is less than the length, else we'll
1453 // be losing some data, CRM-7481
1454 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1455 // need to do a few things here
1456
1457 // 1. lets find a new length
1458 $newLength = $customFields[$customFieldId]['text_length'];
1459 $minLength = strlen($value);
1460 while ($newLength < $minLength) {
1461 $newLength = $newLength * 2;
1462 }
1463
1464 // set the custom field meta data to have a length larger than value
1465 // alter the custom value table column to match this length
1466 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1467 }
1468 }
1469
1470 $date = NULL;
1471 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1472 if (!CRM_Utils_System::isNull($value)) {
1473 $format = $customFields[$customFieldId]['date_format'];
1474 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1475 }
1476 $value = $date;
1477 }
1478
1479 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1480 $customFields[$customFieldId]['data_type'] == 'Money'
1481 ) {
1482 if (!$value) {
1483 $value = 0;
1484 }
1485
1486 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1487 $value = CRM_Utils_Rule::cleanMoney($value);
1488 }
1489 }
1490
1491 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1492 $customFields[$customFieldId]['data_type'] == 'Country'
1493 ) &&
1494 empty($value)
1495 ) {
1496 // CRM-3415
1497 $value = 0;
1498 }
1499
1500 $fileID = NULL;
1501
1502 if ($customFields[$customFieldId]['data_type'] == 'File') {
1503 if (empty($value)) {
1504 return;
1505 }
1506
1507 $config = CRM_Core_Config::singleton();
1508
1509 // If we are already passing the file id as a value then retrieve and set the file data
1510 if (CRM_Utils_Rule::integer($value)) {
1511 $fileDAO = new CRM_Core_DAO_File();
1512 $fileDAO->id = $value;
1513 $fileDAO->find(TRUE);
1514 if ($fileDAO->N) {
1515 $fileID = $value;
1516 $fName = $fileDAO->uri;
1517 $mimeType = $fileDAO->mime_type;
1518 }
1519 }
1520 else {
1521 $fName = $value['name'];
1522 $mimeType = $value['type'];
1523 }
1524
1525 $filename = pathinfo($fName, PATHINFO_BASENAME);
1526
1527 // rename this file to go into the secure directory only if
1528 // user has uploaded new file not existing verfied on the basis of $fileID
1529 if (empty($fileID) && !rename($fName, $config->customFileUploadDir . $filename)) {
1530 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
1531 }
1532
1533 if ($customValueId && empty($fileID)) {
1534 $query = "
1535 SELECT $columnName
1536 FROM $tableName
1537 WHERE id = %1";
1538 $params = [1 => [$customValueId, 'Integer']];
1539 $fileID = CRM_Core_DAO::singleValueQuery($query, $params);
1540 }
1541
1542 $fileDAO = new CRM_Core_DAO_File();
1543
1544 if ($fileID) {
1545 $fileDAO->id = $fileID;
1546 }
1547
1548 $fileDAO->uri = $filename;
1549 $fileDAO->mime_type = $mimeType;
1550 $fileDAO->upload_date = date('YmdHis');
1551 $fileDAO->save();
1552 $fileID = $fileDAO->id;
1553 $value = $filename;
1554 }
1555
1556 if (!is_array($customFormatted)) {
1557 $customFormatted = [];
1558 }
1559
1560 if (!array_key_exists($customFieldId, $customFormatted)) {
1561 $customFormatted[$customFieldId] = [];
1562 }
1563
1564 $index = -1;
1565 if ($customValueId) {
1566 $index = $customValueId;
1567 }
1568
1569 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1570 $customFormatted[$customFieldId][$index] = [];
1571 }
1572 $customFormatted[$customFieldId][$index] = [
1573 'id' => $customValueId > 0 ? $customValueId : NULL,
1574 'value' => $value,
1575 'type' => $customFields[$customFieldId]['data_type'],
1576 'custom_field_id' => $customFieldId,
1577 'custom_group_id' => $groupID,
1578 'table_name' => $tableName,
1579 'column_name' => $columnName,
1580 'file_id' => $fileID,
1581 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1582 ];
1583
1584 //we need to sort so that custom fields are created in the order of entry
1585 krsort($customFormatted[$customFieldId]);
1586 return $customFormatted;
1587 }
1588
1589 /**
1590 * Get default custom table schema.
1591 *
1592 * @param array $params
1593 *
1594 * @return array
1595 */
1596 public static function defaultCustomTableSchema($params) {
1597 // add the id and extends_id
1598 $table = [
1599 'name' => $params['name'],
1600 'is_multiple' => $params['is_multiple'],
1601 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1602 'fields' => [
1603 [
1604 'name' => 'id',
1605 'type' => 'int unsigned',
1606 'primary' => TRUE,
1607 'required' => TRUE,
1608 'attributes' => 'AUTO_INCREMENT',
1609 'comment' => 'Default MySQL primary key',
1610 ],
1611 [
1612 'name' => 'entity_id',
1613 'type' => 'int unsigned',
1614 'required' => TRUE,
1615 'comment' => 'Table that this extends',
1616 'fk_table_name' => $params['extends_name'],
1617 'fk_field_name' => 'id',
1618 'fk_attributes' => 'ON DELETE CASCADE',
1619 ],
1620 ],
1621 ];
1622
1623 if (!$params['is_multiple']) {
1624 $table['indexes'] = [
1625 [
1626 'unique' => TRUE,
1627 'field_name_1' => 'entity_id',
1628 ],
1629 ];
1630 }
1631 return $table;
1632 }
1633
1634 /**
1635 * Create custom field.
1636 *
1637 * @param CRM_Core_DAO_CustomField $field
1638 * @param string $operation
1639 */
1640 public static function createField($field, $operation) {
1641 $sql = str_repeat(' ', 8);
1642 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id, 'table_name');
1643 $sql .= "ALTER TABLE " . $tableName;
1644 $sql .= self::getAlterFieldSQL($field, $operation);
1645
1646 // CRM-7007: do not i18n-rewrite this query
1647 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1648
1649 $config = CRM_Core_Config::singleton();
1650 if ($config->logging) {
1651 // CRM-16717 not sure why this was originally limited to add.
1652 // For example custom tables can have field length changes - which need to flow through to logging.
1653 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1654 if ($operation === 'add' || $operation === 'modify') {
1655 $logging = new CRM_Logging_Schema();
1656 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name]]);
1657 }
1658 }
1659
1660 Civi::service('sql_triggers')->rebuild($tableName, TRUE);
1661 }
1662
1663 /**
1664 * @param CRM_Core_DAO_CustomField $field
1665 * @param string $operation
1666 *
1667 * @return bool
1668 */
1669 public static function getAlterFieldSQL($field, $operation) {
1670 $indexExist = $operation === 'add' ? FALSE : CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $field->id, 'is_searchable');
1671 $params = self::prepareCreateParams($field, $operation);
1672 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1673 // a function only used by Custom Field creation...
1674 $params['required'] = FALSE;
1675 return CRM_Core_BAO_SchemaHandler::getFieldAlterSQL($params, $indexExist);
1676 }
1677
1678 /**
1679 * Determine whether it would be safe to move a field.
1680 *
1681 * @param int $fieldID
1682 * FK to civicrm_custom_field.
1683 * @param int $newGroupID
1684 * FK to civicrm_custom_group.
1685 *
1686 * @return array
1687 * array(string) or TRUE
1688 */
1689 public static function _moveFieldValidate($fieldID, $newGroupID) {
1690 $errors = [];
1691
1692 $field = new CRM_Core_DAO_CustomField();
1693 $field->id = $fieldID;
1694 if (!$field->find(TRUE)) {
1695 $errors['fieldID'] = 'Invalid ID for custom field';
1696 return $errors;
1697 }
1698
1699 $oldGroup = new CRM_Core_DAO_CustomGroup();
1700 $oldGroup->id = $field->custom_group_id;
1701 if (!$oldGroup->find(TRUE)) {
1702 $errors['fieldID'] = 'Invalid ID for old custom group';
1703 return $errors;
1704 }
1705
1706 $newGroup = new CRM_Core_DAO_CustomGroup();
1707 $newGroup->id = $newGroupID;
1708 if (!$newGroup->find(TRUE)) {
1709 $errors['newGroupID'] = 'Invalid ID for new custom group';
1710 return $errors;
1711 }
1712
1713 $query = "
1714 SELECT b.id
1715 FROM civicrm_custom_field a
1716 INNER JOIN civicrm_custom_field b
1717 WHERE a.id = %1
1718 AND a.label = b.label
1719 AND b.custom_group_id = %2
1720 ";
1721 $params = [
1722 1 => [$field->id, 'Integer'],
1723 2 => [$newGroup->id, 'Integer'],
1724 ];
1725 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1726 if ($count > 0) {
1727 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1728 }
1729
1730 $tableName = $oldGroup->table_name;
1731 $columnName = $field->column_name;
1732
1733 $query = "
1734 SELECT count(*)
1735 FROM $tableName
1736 WHERE $columnName is not null
1737 ";
1738 $count = CRM_Core_DAO::singleValueQuery($query);
1739 if ($count > 0) {
1740 $query = "
1741 SELECT extends
1742 FROM civicrm_custom_group
1743 WHERE id IN ( %1, %2 )
1744 ";
1745 $params = [
1746 1 => [$oldGroup->id, 'Integer'],
1747 2 => [$newGroup->id, 'Integer'],
1748 ];
1749
1750 $dao = CRM_Core_DAO::executeQuery($query, $params);
1751 $extends = [];
1752 while ($dao->fetch()) {
1753 $extends[] = $dao->extends;
1754 }
1755 if ($extends[0] != $extends[1]) {
1756 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1757 }
1758 }
1759
1760 return empty($errors) ? TRUE : $errors;
1761 }
1762
1763 /**
1764 * Move a custom data field from one group (table) to another.
1765 *
1766 * @param int $fieldID
1767 * FK to civicrm_custom_field.
1768 * @param int $newGroupID
1769 * FK to civicrm_custom_group.
1770 */
1771 public static function moveField($fieldID, $newGroupID) {
1772 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
1773 if (TRUE !== $validation) {
1774 CRM_Core_Error::fatal(implode(' ', $validation));
1775 }
1776 $field = new CRM_Core_DAO_CustomField();
1777 $field->id = $fieldID;
1778 $field->find(TRUE);
1779
1780 $newGroup = new CRM_Core_DAO_CustomGroup();
1781 $newGroup->id = $newGroupID;
1782 $newGroup->find(TRUE);
1783
1784 $oldGroup = new CRM_Core_DAO_CustomGroup();
1785 $oldGroup->id = $field->custom_group_id;
1786 $oldGroup->find(TRUE);
1787
1788 $add = clone$field;
1789 $add->custom_group_id = $newGroup->id;
1790 self::createField($add, 'add');
1791
1792 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1793 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1794 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1795 ";
1796 CRM_Core_DAO::executeQuery($sql);
1797
1798 $del = clone$field;
1799 $del->custom_group_id = $oldGroup->id;
1800 self::createField($del, 'delete');
1801
1802 $add->save();
1803
1804 CRM_Utils_System::flushCache();
1805 }
1806
1807 /**
1808 * Create an option value for a custom field option group ID.
1809 *
1810 * @param array $params
1811 * @param string $value
1812 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1813 * @param string $index
1814 * @param string $dataType
1815 */
1816 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup $optionGroup, $index, $dataType) {
1817 if (strlen(trim($value))) {
1818 $optionValue = new CRM_Core_DAO_OptionValue();
1819 $optionValue->option_group_id = $optionGroup->id;
1820 $optionValue->label = $params['option_label'][$index];
1821 $optionValue->name = $params['option_name'][$index] ?? CRM_Utils_String::titleToVar($params['option_label'][$index]);
1822 switch ($dataType) {
1823 case 'Money':
1824 $optionValue->value = CRM_Utils_Rule::cleanMoney($value);
1825 break;
1826
1827 case 'Int':
1828 $optionValue->value = intval($value);
1829 break;
1830
1831 case 'Float':
1832 $optionValue->value = floatval($value);
1833 break;
1834
1835 default:
1836 $optionValue->value = trim($value);
1837 }
1838
1839 $optionValue->weight = $params['option_weight'][$index];
1840 $optionValue->is_active = $params['option_status'][$index] ?? FALSE;
1841 $optionValue->description = $params['option_description'][$index] ?? NULL;
1842 $optionValue->color = $params['option_color'][$index] ?? NULL;
1843 $optionValue->icon = $params['option_icon'][$index] ?? NULL;
1844 $optionValue->save();
1845 }
1846 }
1847
1848 /**
1849 * Prepare for the create operation.
1850 *
1851 * Munge params, create the option values if needed.
1852 *
1853 * This could be called by a single create or a batchCreate.
1854 *
1855 * @param array $params
1856 *
1857 * @return array
1858 */
1859 protected static function prepareCreate($params) {
1860 $op = empty($params['id']) ? 'create' : 'edit';
1861 CRM_Utils_Hook::pre($op, 'CustomField', CRM_Utils_Array::value('id', $params), $params);
1862 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1863 if ($op === 'create') {
1864 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
1865 if (!isset($params['column_name'])) {
1866 // if add mode & column_name not present, calculate it.
1867 $params['column_name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 32));
1868 }
1869 if (!isset($params['name'])) {
1870 $params['name'] = CRM_Utils_String::munge($params['label'], '_', 64);
1871 }
1872 }
1873 else {
1874 $params['column_name'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1875 }
1876
1877 $htmlType = $params['html_type'] ?? NULL;
1878 $dataType = $params['data_type'] ?? NULL;
1879
1880 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1881 $params['date_format'] = Civi::settings()->get('dateInputFormat');
1882 }
1883
1884 if ($htmlType === 'CheckBox' || $htmlType === 'Multi-Select') {
1885 if (isset($params['default_checkbox_option'])) {
1886 $defaultArray = [];
1887 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1888 if ($params['option_value'][$v]) {
1889 $defaultArray[] = $params['option_value'][$v];
1890 }
1891 }
1892
1893 if (!empty($defaultArray)) {
1894 // also add the separator before and after the value per new convention (CRM-1604)
1895 $params['default_value'] = CRM_Utils_Array::implodePadded($defaultArray);
1896 }
1897 }
1898 else {
1899 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1900 $params['default_value'] = $params['option_value'][$params['default_option']];
1901 }
1902 }
1903 }
1904
1905 // create any option group & values if required
1906 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1907 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
1908 //CRM-16659: if option_value then create an option group for this custom field.
1909 if ($params['option_type'] == 1 && (empty($params['option_group_id']) || !empty($params['option_value']))) {
1910 // first create an option group for this custom group
1911 $optionGroup = new CRM_Core_DAO_OptionGroup();
1912 $optionGroup->name = "{$params['column_name']}_" . date('YmdHis');
1913 $optionGroup->title = $params['label'];
1914 $optionGroup->is_active = 1;
1915 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1916 $optionGroup->is_reserved = 0;
1917 $optionGroup->data_type = $dataType;
1918 $optionGroup->save();
1919 $params['option_group_id'] = $optionGroup->id;
1920 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1921 foreach ($params['option_value'] as $k => $v) {
1922 self::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1923 }
1924 }
1925 }
1926 }
1927
1928 // check for orphan option groups
1929 if (!empty($params['option_group_id'])) {
1930 if (!empty($params['id'])) {
1931 self::fixOptionGroups($params['id'], $params['option_group_id']);
1932 }
1933
1934 // if we do not have a default value
1935 // retrieve it from one of the other custom fields which use this option group
1936 if (empty($params['default_value'])) {
1937 //don't insert only value separator as default value, CRM-4579
1938 $defaultValue = self::getOptionGroupDefault($params['option_group_id'], $htmlType);
1939
1940 if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaultValue))) {
1941 $params['default_value'] = $defaultValue;
1942 }
1943 }
1944 }
1945
1946 // Set default textarea attributes
1947 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
1948 $params['attributes'] = 'rows=4, cols=60';
1949 }
1950 return $params;
1951 }
1952
1953 /**
1954 * Create database entry for custom field and related option groups.
1955 *
1956 * @param array $params
1957 *
1958 * @return CRM_Core_DAO_CustomField
1959 */
1960 protected static function createCustomFieldRecord($params) {
1961 $transaction = new CRM_Core_Transaction();
1962 $params = self::prepareCreate($params);
1963
1964 $customField = new CRM_Core_DAO_CustomField();
1965 $customField->copyValues($params);
1966 $customField->save();
1967
1968 //create/drop the index when we toggle the is_searchable flag
1969 $op = empty($params['id']) ? 'add' : 'modify';
1970 if ($op !== 'modify') {
1971 if ($params['is_append_field_id_to_column_name']) {
1972 $params['column_name'] .= "_{$customField->id}";
1973 }
1974 $customField->column_name = $params['column_name'];
1975 $customField->save();
1976 }
1977
1978 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
1979 $transaction->commit();
1980
1981 // make sure all values are present in the object for further processing
1982 $customField->find(TRUE);
1983 return $customField;
1984 }
1985
1986 /**
1987 * Move custom data from one contact to another.
1988 *
1989 * This is currently the start of a refactoring. The theory is each
1990 * entity could have a 'move' function with a DAO default one to fall back on.
1991 *
1992 * At the moment this only does a small part of the process - ie deleting a file field that
1993 * is about to be overwritten. However, the goal is the whole process around the move for
1994 * custom data should be in here.
1995 *
1996 * This is currently called by the merge class but it makes sense that api could
1997 * expose move actions as moving (e.g) contributions feels like a common
1998 * ask that should be handled by the form layer.
1999 *
2000 * @param int $oldContactID
2001 * @param int $newContactID
2002 * @param int[] $fieldIDs
2003 * Optional list field ids to move.
2004 *
2005 * @throws \CiviCRM_API3_Exception
2006 * @throws \Exception
2007 */
2008 public function move($oldContactID, $newContactID, $fieldIDs) {
2009 if (empty($fieldIDs)) {
2010 return;
2011 }
2012 $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'];
2013 $return = [];
2014 foreach ($fieldIDs as $fieldID) {
2015 $return[] = 'custom_' . $fieldID;
2016 }
2017 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2018 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2019
2020 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2021 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2022 $fieldTypesNotHandledInMergeAttempt = ['File'];
2023 foreach ($fields as $field) {
2024 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2025 if ($field['data_type'] === 'File' && !$isMultiple) {
2026 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2027 CRM_Core_BAO_File::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2028 }
2029 if (!empty($oldContact['custom_' . $field['id']])) {
2030 CRM_Core_DAO::executeQuery("
2031 UPDATE civicrm_entity_file
2032 SET entity_id = $newContactID
2033 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2034 );
2035 }
2036 }
2037 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2038 CRM_Core_DAO::executeQuery(
2039 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2040 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2041 ON DUPLICATE KEY UPDATE
2042 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2043 ");
2044 }
2045 }
2046 }
2047
2048 /**
2049 * Get the database table name and column name for a custom field.
2050 *
2051 * @param int $fieldID
2052 * The fieldID of the custom field.
2053 * @param bool $force
2054 * Force the sql to be run again (primarily used for tests).
2055 *
2056 * @return array
2057 * fatal is fieldID does not exists, else array of tableName, columnName
2058 * @throws \Exception
2059 */
2060 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2061 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2062 $cache = CRM_Utils_Cache::singleton();
2063 $fieldValues = $cache->get($cacheKey);
2064 if (empty($fieldValues) || $force) {
2065 $query = "
2066 SELECT cg.table_name, cf.column_name, cg.id
2067 FROM civicrm_custom_group cg,
2068 civicrm_custom_field cf
2069 WHERE cf.custom_group_id = cg.id
2070 AND cf.id = %1";
2071 $params = [1 => [$fieldID, 'Integer']];
2072 $dao = CRM_Core_DAO::executeQuery($query, $params);
2073
2074 if (!$dao->fetch()) {
2075 CRM_Core_Error::fatal();
2076 }
2077 $fieldValues = [$dao->table_name, $dao->column_name, $dao->id];
2078 $cache->set($cacheKey, $fieldValues);
2079 }
2080 return $fieldValues;
2081 }
2082
2083 /**
2084 * Get custom option groups.
2085 *
2086 * @deprecated Use the API OptionGroup.get
2087 *
2088 * @param array $includeFieldIds
2089 * Ids of custom fields for which option groups must be included.
2090 *
2091 * Currently this is required in the cases where option groups are to be included
2092 * for inactive fields : CRM-5369
2093 *
2094 * @return mixed
2095 */
2096 public static function customOptionGroup($includeFieldIds = NULL) {
2097 static $customOptionGroup = NULL;
2098
2099 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
2100 if ($cacheKey == 'force') {
2101 $customOptionGroup[$cacheKey] = NULL;
2102 }
2103
2104 if (empty($customOptionGroup[$cacheKey])) {
2105 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2106
2107 //support for single as well as array format.
2108 if (!empty($includeFieldIds)) {
2109 if (is_array($includeFieldIds)) {
2110 $includeFieldIds = implode(',', $includeFieldIds);
2111 }
2112 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2113 }
2114
2115 $query = "
2116 SELECT g.id, g.title
2117 FROM civicrm_option_group g
2118 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2119 WHERE {$whereClause}";
2120
2121 $dao = CRM_Core_DAO::executeQuery($query);
2122 while ($dao->fetch()) {
2123 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
2124 }
2125 }
2126
2127 return $customOptionGroup[$cacheKey];
2128 }
2129
2130 /**
2131 * Get defaults for new entity.
2132 *
2133 * @return array
2134 */
2135 public static function getDefaults() {
2136 return [
2137 'is_required' => FALSE,
2138 'is_searchable' => FALSE,
2139 'in_selector' => FALSE,
2140 'is_search_range' => FALSE,
2141 //CRM-15792 - Custom field gets disabled if is_active not set
2142 // this would ideally be a mysql default.
2143 'is_active' => TRUE,
2144 'is_view' => FALSE,
2145 ];
2146 }
2147
2148 /**
2149 * Fix orphan groups.
2150 *
2151 * @param int $customFieldId
2152 * Custom field id.
2153 * @param int $optionGroupId
2154 * Option group id.
2155 */
2156 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2157 // check if option group belongs to any custom Field else delete
2158 // get the current option group
2159 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2160 $customFieldId,
2161 'option_group_id'
2162 );
2163 // get the updated option group
2164 // if both are same return
2165 if (!$currentOptionGroupId || $currentOptionGroupId == $optionGroupId) {
2166 return;
2167 }
2168
2169 // check if option group is related to any other field
2170 self::checkOptionGroup($currentOptionGroupId);
2171 }
2172
2173 /**
2174 * Check if option group is related to more than one custom field.
2175 *
2176 * @param int $optionGroupId
2177 * Option group id.
2178 */
2179 public static function checkOptionGroup($optionGroupId) {
2180 $query = "
2181 SELECT count(*)
2182 FROM civicrm_custom_field
2183 WHERE option_group_id = {$optionGroupId}";
2184
2185 $count = CRM_Core_DAO::singleValueQuery($query);
2186
2187 if ($count < 2) {
2188 //delete the option group
2189 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2190 }
2191 }
2192
2193 /**
2194 * Get option group default.
2195 *
2196 * @param int $optionGroupId
2197 * @param string $htmlType
2198 *
2199 * @return null|string
2200 */
2201 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2202 $query = "
2203 SELECT default_value, html_type
2204 FROM civicrm_custom_field
2205 WHERE option_group_id = {$optionGroupId}
2206 AND default_value IS NOT NULL
2207 ORDER BY html_type";
2208
2209 $dao = CRM_Core_DAO::executeQuery($query);
2210 $defaultValue = NULL;
2211 $defaultHTMLType = NULL;
2212 while ($dao->fetch()) {
2213 if ($dao->html_type == $htmlType) {
2214 return $dao->default_value;
2215 }
2216 if ($defaultValue == NULL) {
2217 $defaultValue = $dao->default_value;
2218 $defaultHTMLType = $dao->html_type;
2219 }
2220 }
2221
2222 // some conversions are needed if either the old or new has a html type which has potential
2223 // multiple default values.
2224 if (($htmlType == 'CheckBox' || $htmlType == 'Multi-Select') &&
2225 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2226 ) {
2227 $defaultValue = CRM_Core_DAO::VALUE_SEPARATOR . $defaultValue . CRM_Core_DAO::VALUE_SEPARATOR;
2228 }
2229 elseif (($defaultHTMLType == 'CheckBox' || $defaultHTMLType == 'Multi-Select') &&
2230 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2231 ) {
2232 $defaultValue = substr($defaultValue, 1, -1);
2233 $values = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2234 substr($defaultValue, 1, -1)
2235 );
2236 $defaultValue = $values[0];
2237 }
2238
2239 return $defaultValue;
2240 }
2241
2242 /**
2243 * Post process function.
2244 *
2245 * @param array $params
2246 * @param int $entityID
2247 * @param string $customFieldExtends
2248 * @param bool $inline
2249 * @param bool $checkPermissions
2250 *
2251 * @return array
2252 */
2253 public static function postProcess(
2254 &$params,
2255 $entityID,
2256 $customFieldExtends,
2257 $inline = FALSE,
2258 $checkPermissions = TRUE
2259 ) {
2260 $customData = [];
2261
2262 foreach ($params as $key => $value) {
2263 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE)) {
2264
2265 // for autocomplete transfer hidden value instead of label
2266 if ($params[$key] && isset($params[$key . '_id'])) {
2267 $value = $params[$key . '_id'];
2268 }
2269
2270 // we need to append time with date
2271 if ($params[$key] && isset($params[$key . '_time'])) {
2272 $value .= ' ' . $params[$key . '_time'];
2273 }
2274
2275 CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0],
2276 $customData,
2277 $value,
2278 $customFieldExtends,
2279 $customFieldInfo[1],
2280 $entityID,
2281 $inline,
2282 $checkPermissions
2283 );
2284 }
2285 }
2286 return $customData;
2287 }
2288
2289 /**
2290 * Get custom field ID from field/group name/title.
2291 *
2292 * @param string $fieldName Field name or label
2293 * @param string|null $groupName (Optional) Group name or label
2294 * @param bool $fullString Whether to return "custom_123" or "123"
2295 *
2296 * @return string|int|null
2297 * @throws \CiviCRM_API3_Exception
2298 */
2299 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2300 $cacheKey = $groupName . '.' . $fieldName;
2301 if (!isset(Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2302 $customFieldParams = [
2303 'name' => $fieldName,
2304 'label' => $fieldName,
2305 'options' => ['or' => [["name", "label"]]],
2306 ];
2307
2308 if ($groupName) {
2309 $customFieldParams['custom_group_id.name'] = $groupName;
2310 $customFieldParams['custom_group_id.title'] = $groupName;
2311 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2312 }
2313
2314 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2315
2316 if (empty($field['id'])) {
2317 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2318 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2319 }
2320 else {
2321 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2322 Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2323 }
2324 }
2325
2326 if ($fullString) {
2327 return Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2328 }
2329 return Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2330 }
2331
2332 /**
2333 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2334 *
2335 * @param array $ids
2336 *
2337 * @return array
2338 */
2339 public static function getNameFromID($ids) {
2340 if (is_array($ids)) {
2341 $ids = implode(',', $ids);
2342 }
2343 $sql = "
2344 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2345 FROM civicrm_custom_field f
2346 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2347 WHERE f.id IN ($ids)";
2348
2349 $dao = CRM_Core_DAO::executeQuery($sql);
2350 $result = [];
2351 while ($dao->fetch()) {
2352 $result[$dao->id] = [
2353 'field_name' => $dao->field_name,
2354 'field_label' => $dao->field_label,
2355 'group_name' => $dao->group_name,
2356 'group_title' => $dao->group_title,
2357 ];
2358 }
2359 return $result;
2360 }
2361
2362 /**
2363 * Validate custom data.
2364 *
2365 * @param array $params
2366 * Custom data submitted.
2367 * ie array( 'custom_1' => 'validate me' );
2368 *
2369 * @return array
2370 * validation errors.
2371 */
2372 public static function validateCustomData($params) {
2373 $errors = [];
2374 if (!is_array($params) || empty($params)) {
2375 return $errors;
2376 }
2377
2378 //pick up profile fields.
2379 $profileFields = [];
2380 $ufGroupId = $params['ufGroupId'] ?? NULL;
2381 if ($ufGroupId) {
2382 $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId,
2383 FALSE,
2384 CRM_Core_Action::VIEW
2385 );
2386 }
2387
2388 //lets start w/ params.
2389 foreach ($params as $key => $value) {
2390 $customFieldID = self::getKeyID($key);
2391 if (!$customFieldID) {
2392 continue;
2393 }
2394
2395 //load the structural info for given field.
2396 $field = new CRM_Core_DAO_CustomField();
2397 $field->id = $customFieldID;
2398 if (!$field->find(TRUE)) {
2399 continue;
2400 }
2401 $dataType = $field->data_type;
2402
2403 $profileField = CRM_Utils_Array::value($key, $profileFields, []);
2404 $fieldTitle = $profileField['title'] ?? NULL;
2405 $isRequired = $profileField['is_required'] ?? NULL;
2406 if (!$fieldTitle) {
2407 $fieldTitle = $field->label;
2408 }
2409
2410 //no need to validate.
2411 if (CRM_Utils_System::isNull($value) && !$isRequired) {
2412 continue;
2413 }
2414
2415 //lets validate first for required field.
2416 if ($isRequired && CRM_Utils_System::isNull($value)) {
2417 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2418 continue;
2419 }
2420
2421 //now time to take care of custom field form rules.
2422 $ruleName = $errorMsg = NULL;
2423 switch ($dataType) {
2424 case 'Int':
2425 $ruleName = 'integer';
2426 $errorMsg = ts('%1 must be an integer (whole number).',
2427 array(1 => $fieldTitle)
2428 );
2429 break;
2430
2431 case 'Money':
2432 $ruleName = 'money';
2433 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2434 array(1 => $fieldTitle)
2435 );
2436 break;
2437
2438 case 'Float':
2439 $ruleName = 'numeric';
2440 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2441 array(1 => $fieldTitle)
2442 );
2443 break;
2444
2445 case 'Link':
2446 $ruleName = 'wikiURL';
2447 $errorMsg = ts('%1 must be valid Website.',
2448 array(1 => $fieldTitle)
2449 );
2450 break;
2451 }
2452
2453 if ($ruleName && !CRM_Utils_System::isNull($value)) {
2454 $valid = FALSE;
2455 $funName = "CRM_Utils_Rule::{$ruleName}";
2456 if (is_callable($funName)) {
2457 $valid = call_user_func($funName, $value);
2458 }
2459 if (!$valid) {
2460 $errors[$key] = $errorMsg;
2461 }
2462 }
2463 }
2464
2465 return $errors;
2466 }
2467
2468 /**
2469 * Is this field a multi record field.
2470 *
2471 * @param int $customId
2472 *
2473 * @return bool
2474 */
2475 public static function isMultiRecordField($customId) {
2476 $isMultipleWithGid = FALSE;
2477 if (!is_numeric($customId)) {
2478 $customId = self::getKeyID($customId);
2479 }
2480 if (is_numeric($customId)) {
2481 $sql = "SELECT cg.id cgId
2482 FROM civicrm_custom_group cg
2483 INNER JOIN civicrm_custom_field cf
2484 ON cg.id = cf.custom_group_id
2485 WHERE cf.id = %1 AND cg.is_multiple = 1";
2486 $params[1] = [$customId, 'Integer'];
2487 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2488 if ($dao->fetch()) {
2489 if ($dao->cgId) {
2490 $isMultipleWithGid = $dao->cgId;
2491 }
2492 }
2493 }
2494
2495 return $isMultipleWithGid;
2496 }
2497
2498 /**
2499 * Does this field type have any select options?
2500 *
2501 * @param array $field
2502 *
2503 * @return bool
2504 */
2505 public static function hasOptions($field) {
2506 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2507 $field = (array) $field;
2508 // This will include boolean fields with Yes/No options.
2509 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2510 return TRUE;
2511 }
2512 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2513 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2514 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2515 return FALSE;
2516 }
2517 if (strpos($field['html_type'], 'Select') !== FALSE) {
2518 return TRUE;
2519 }
2520 return !empty($field['option_group_id']);
2521 }
2522
2523 /**
2524 * Does this field store a serialized string?
2525 *
2526 * @param array|object $field
2527 *
2528 * @return bool
2529 */
2530 public static function isSerialized($field) {
2531 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2532 $html_type = is_object($field) ? $field->html_type : $field['html_type'];
2533 // 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.
2534 return ($html_type === 'CheckBox' || strpos($html_type, 'Multi') !== FALSE);
2535 }
2536
2537 /**
2538 * Get api entity for this field
2539 *
2540 * @return string
2541 */
2542 public function getEntity() {
2543 $entity = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id, 'extends');
2544 return in_array($entity, ['Individual', 'Household', 'Organization']) ? 'Contact' : $entity;
2545 }
2546
2547 /**
2548 * Set pseudoconstant properties for field metadata.
2549 *
2550 * @param array $field
2551 * @param string|null $optionGroupName
2552 */
2553 private static function getOptionsForField(&$field, $optionGroupName) {
2554 if ($optionGroupName) {
2555 $field['pseudoconstant'] = [
2556 'optionGroupName' => $optionGroupName,
2557 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2558 ];
2559 }
2560 elseif ($field['data_type'] == 'Boolean') {
2561 $field['pseudoconstant'] = [
2562 'callback' => 'CRM_Core_SelectValues::boolean',
2563 ];
2564 }
2565 elseif ($field['data_type'] == 'Country') {
2566 $field['pseudoconstant'] = [
2567 'table' => 'civicrm_country',
2568 'keyColumn' => 'id',
2569 'labelColumn' => 'name',
2570 'nameColumn' => 'iso_code',
2571 ];
2572 }
2573 elseif ($field['data_type'] == 'StateProvince') {
2574 $field['pseudoconstant'] = [
2575 'table' => 'civicrm_state_province',
2576 'keyColumn' => 'id',
2577 'labelColumn' => 'name',
2578 ];
2579 }
2580 }
2581
2582 /**
2583 * @param CRM_Core_DAO_CustomField $field
2584 * @param 'add|modify' $operation
2585 *
2586 * @return array
2587 */
2588 protected static function prepareCreateParams($field, $operation) {
2589 $tableName = CRM_Core_DAO::getFieldValue(
2590 'CRM_Core_DAO_CustomGroup',
2591 $field->custom_group_id,
2592 'table_name'
2593 );
2594
2595 $params = [
2596 'table_name' => $tableName,
2597 'operation' => $operation,
2598 'name' => $field->column_name,
2599 'type' => CRM_Core_BAO_CustomValueTable::fieldToSQLType(
2600 $field->data_type,
2601 $field->text_length
2602 ),
2603 'required' => $field->is_required,
2604 'searchable' => $field->is_searchable,
2605 ];
2606
2607 if ($operation == 'delete') {
2608 $fkName = "{$tableName}_{$field->column_name}";
2609 if (strlen($fkName) >= 48) {
2610 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2611 }
2612 $params['fkName'] = $fkName;
2613 }
2614 if ($field->data_type == 'Country' && !self::isSerialized($field)) {
2615 $params['fk_table_name'] = 'civicrm_country';
2616 $params['fk_field_name'] = 'id';
2617 $params['fk_attributes'] = 'ON DELETE SET NULL';
2618 }
2619 elseif ($field->data_type == 'StateProvince' && !self::isSerialized($field)) {
2620 $params['fk_table_name'] = 'civicrm_state_province';
2621 $params['fk_field_name'] = 'id';
2622 $params['fk_attributes'] = 'ON DELETE SET NULL';
2623 }
2624 elseif ($field->data_type == 'StateProvince' || $field->data_type == 'Country') {
2625 $params['type'] = 'varchar(255)';
2626 }
2627 elseif ($field->data_type == 'File') {
2628 $params['fk_table_name'] = 'civicrm_file';
2629 $params['fk_field_name'] = 'id';
2630 $params['fk_attributes'] = 'ON DELETE SET NULL';
2631 }
2632 elseif ($field->data_type == 'ContactReference') {
2633 $params['fk_table_name'] = 'civicrm_contact';
2634 $params['fk_field_name'] = 'id';
2635 $params['fk_attributes'] = 'ON DELETE SET NULL';
2636 }
2637 if (isset($field->default_value)) {
2638 $params['default'] = "'{$field->default_value}'";
2639 }
2640 return $params;
2641 }
2642
2643 }