Merge pull request #22966 from eileenmcnaughton/retrieve
[civicrm-core.git] / api / v3 / 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 * This api exposes CiviCRM custom field.
14 *
15 * @package CiviCRM_APIv3
16 */
17
18 /**
19 * Create a 'custom field' within a custom field group.
20 *
21 * We also empty the static var in the getfields
22 * function after deletion so that the field is available for us (getfields
23 * manages date conversion among other things
24 *
25 * @param array $params
26 * Array per getfields metadata.
27 *
28 * @return array
29 * API success array
30 * @throws \CiviCRM_API3_Exception
31 */
32 function civicrm_api3_custom_field_create(array $params): array {
33
34 // Legacy handling for old way of naming serialized fields
35 if (!empty($params['html_type'])) {
36 if ($params['html_type'] === 'CheckBox' || strpos($params['html_type'], 'Multi-') === 0) {
37 $params['serialize'] = 1;
38 }
39 $params['html_type'] = str_replace(['Multi-Select', 'Select Country', 'Select State/Province'], 'Select', $params['html_type']);
40 }
41
42 // Array created for passing options in params.
43 if (isset($params['option_values']) && is_array($params['option_values'])) {
44 $weight = 0;
45 foreach ($params['option_values'] as $key => $value) {
46 // Translate simple key/value pairs into full-blown option values
47 if (!is_array($value)) {
48 $value = [
49 'label' => $value,
50 'value' => $key,
51 'is_active' => 1,
52 'weight' => $weight,
53 ];
54 $key = $weight++;
55 }
56 $params['option_label'][$key] = $value['label'];
57 $params['option_value'][$key] = $value['value'];
58 $params['option_status'][$key] = $value['is_active'];
59 $params['option_weight'][$key] = $value['weight'];
60 }
61 }
62 elseif (
63 // Legacy handling for historical apiv3 behaviour.
64 empty($params['id'])
65 && !empty($params['html_type'])
66 && $params['html_type'] !== 'Text'
67 && empty($params['option_group_id'])
68 && empty($params['option_value'])
69 && in_array($params['data_type'] ?? '', ['String', 'Int', 'Float', 'Money'])) {
70 // Trick the BAO into creating an option group even though no option values exist
71 // because that odd behaviour is locked in via a test.
72 $params['option_value'] = 1;
73 }
74 $values = [];
75 $customField = CRM_Core_BAO_CustomField::create($params);
76 _civicrm_api3_object_to_array_unique_fields($customField, $values[$customField->id]);
77 _civicrm_api3_custom_field_flush_static_caches();
78 return civicrm_api3_create_success($values, $params, 'CustomField', $customField);
79 }
80
81 /**
82 * Flush static caches in functions that might have stored available custom fields.
83 */
84 function _civicrm_api3_custom_field_flush_static_caches() {
85 if (isset(\Civi::$statics['CRM_Core_BAO_OptionGroup']['titles_by_name'])) {
86 unset(\Civi::$statics['CRM_Core_BAO_OptionGroup']['titles_by_name']);
87 }
88 civicrm_api('CustomField', 'getfields', ['version' => 3, 'cache_clear' => 1]);
89 CRM_Core_BAO_UFField::getAvailableFieldsFlat(TRUE);
90 }
91
92 /**
93 * Adjust Metadata for Create action.
94 *
95 * @param array $params
96 * Array of parameters determined by getfields.
97 */
98 function _civicrm_api3_custom_field_create_spec(&$params) {
99 $params['label']['api.required'] = 1;
100 $params['custom_group_id']['api.required'] = 1;
101 $params['is_active']['api.default'] = 1;
102 $params['option_values'] = [
103 'title' => 'Option Values',
104 'description' => "Pass an array of options (value => label) to create this field's option values",
105 ];
106 $params['data_type']['api.default'] = 'String';
107 $params['is_active']['api.default'] = 1;
108 }
109
110 /**
111 * Use this API to delete an existing custom field.
112 *
113 * @param array $params
114 * Array id of the field to be deleted.
115 *
116 * @return array
117 */
118 function civicrm_api3_custom_field_delete($params) {
119 $field = new CRM_Core_BAO_CustomField();
120 $field->id = $params['id'];
121 $field->find(TRUE);
122 $customFieldDelete = CRM_Core_BAO_CustomField::deleteField($field);
123 civicrm_api('CustomField', 'getfields', ['version' => 3, 'cache_clear' => 1]);
124 return $customFieldDelete ? civicrm_api3_create_error('Error while deleting custom field') : civicrm_api3_create_success();
125 }
126
127 /**
128 * Use this API to get existing custom fields.
129 *
130 * @param array $params
131 * Array to search on.
132 *
133 * @return array
134 */
135 function civicrm_api3_custom_field_get($params) {
136 // Legacy handling for serialize property
137 $handleLegacy = (($params['legacy_html_type'] ?? !isset($params['serialize'])) && CRM_Core_BAO_Domain::isDBVersionAtLeast('5.27.alpha1'));
138 if ($handleLegacy && !empty($params['return'])) {
139 if (!is_array($params['return'])) {
140 $params['return'] = explode(',', str_replace(' ', '', $params['return']));
141 }
142 if (!in_array('serialize', $params['return'])) {
143 $params['return'][] = 'serialize';
144 }
145 if (!in_array('data_type', $params['return'])) {
146 $params['return'][] = 'data_type';
147 }
148 }
149 $legacyDataTypes = [
150 'Select State/Province' => 'StateProvince',
151 'Select Country' => 'Country',
152 ];
153 if ($handleLegacy && !empty($params['html_type'])) {
154 $serializedTypes = ['CheckBox', 'Multi-Select', 'Multi-Select Country', 'Multi-Select State/Province'];
155 if (is_string($params['html_type'])) {
156 if (strpos($params['html_type'], 'Multi-Select') === 0) {
157 $params['html_type'] = str_replace('Multi-Select', 'Select', $params['html_type']);
158 $params['serialize'] = 1;
159 }
160 elseif (!in_array($params['html_type'], $serializedTypes)) {
161 $params['serialize'] = 0;
162 }
163 if (isset($legacyDataTypes[$params['html_type']])) {
164 $params['data_type'] = $legacyDataTypes[$params['html_type']];
165 unset($params['html_type']);
166 }
167 }
168 elseif (is_array($params['html_type']) && !empty($params['html_type']['IN'])) {
169 $excludeNonSerialized = !array_diff($params['html_type']['IN'], $serializedTypes);
170 $onlyNonSerialized = !array_intersect($params['html_type']['IN'], $serializedTypes);
171 $params['html_type']['IN'] = array_map(function($val) {
172 return str_replace(['Multi-Select', 'Select Country', 'Select State/Province'], 'Select', $val);
173 }, $params['html_type']['IN']);
174 if ($excludeNonSerialized) {
175 $params['serialize'] = 1;
176 }
177 if ($onlyNonSerialized) {
178 $params['serialize'] = 0;
179 }
180 }
181 }
182
183 $results = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
184
185 if ($handleLegacy && !empty($results['values']) && is_array($results['values'])) {
186 foreach ($results['values'] as $id => &$result) {
187 if (!empty($result['html_type'])) {
188 if (in_array($result['data_type'], $legacyDataTypes)) {
189 $result['html_type'] = array_search($result['data_type'], $legacyDataTypes);
190 }
191 if (!empty($result['serialize']) && $result['html_type'] !== 'Autocomplete-Select') {
192 $result['html_type'] = str_replace('Select', 'Multi-Select', $result['html_type']);
193 }
194 }
195 }
196 }
197
198 return $results;
199 }
200
201 /**
202 * Helper function to validate custom field value.
203 *
204 * @deprecated
205 *
206 * @param string $fieldName
207 * Custom field name (eg: custom_8 ).
208 * @param mixed $value
209 * Field value to be validate.
210 * @param array $fieldDetails
211 * Field Details.
212 * @param array $errors
213 * Collect validation errors.
214 *
215 * @return array|NULL
216 * Validation errors
217 * @todo remove this function - not in use but need to review functionality before
218 * removing as it might be useful in wrapper layer
219 */
220 function _civicrm_api3_custom_field_validate_field($fieldName, $value, $fieldDetails, &$errors = []) {
221 return NULL;
222 //see comment block
223 if (!$value) {
224 return $errors;
225 }
226
227 $dataType = $fieldDetails['data_type'];
228 $htmlType = $fieldDetails['html_type'];
229
230 switch ($dataType) {
231 case 'Int':
232 if (!CRM_Utils_Rule::integer($value)) {
233 $errors[$fieldName] = 'Invalid integer value for ' . $fieldName;
234 }
235 break;
236
237 case 'Float':
238 if (!CRM_Utils_Rule::numeric($value)) {
239 $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
240 }
241 break;
242
243 case 'Money':
244 if (!CRM_Utils_Rule::money($value)) {
245 $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
246 }
247 break;
248
249 case 'Link':
250 if (!CRM_Utils_Rule::url($value)) {
251 $errors[$fieldName] = 'Invalid link for ' . $fieldName;
252 }
253 break;
254
255 case 'Boolean':
256 if ($value != '1' && $value != '0') {
257 $errors[$fieldName] = 'Invalid boolean (use 1 or 0) value for ' . $fieldName;
258 }
259 break;
260
261 case 'Country':
262 if (empty($value)) {
263 break;
264 }
265 if ($htmlType != 'Multi-Select Country' && is_array($value)) {
266 $errors[$fieldName] = 'Invalid country for ' . $fieldName;
267 break;
268 }
269
270 if (!is_array($value)) {
271 $value = [$value];
272 }
273
274 $query = "SELECT count(*) FROM civicrm_country WHERE id IN (" . implode(',', $value) . ")";
275 if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
276 $errors[$fieldName] = 'Invalid country(s) for ' . $fieldName;
277 }
278 break;
279
280 case 'StateProvince':
281 if (empty($value)) {
282 break;
283 }
284
285 if ($htmlType != 'Multi-Select State/Province' && is_array($value)) {
286 $errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
287 break;
288 }
289
290 if (!is_array($value)) {
291 $value = [$value];
292 }
293
294 $query = "
295 SELECT count(*)
296 FROM civicrm_state_province
297 WHERE id IN ('" . implode("','", $value) . "')";
298 if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
299 $errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
300 }
301 break;
302
303 case 'ContactReference':
304 //FIX ME
305 break;
306 }
307
308 if (in_array($htmlType, ['Select', 'Multi-Select', 'CheckBox', 'Radio'])
309 && !isset($errors[$fieldName])
310 ) {
311 $options = CRM_Core_OptionGroup::valuesByID($fieldDetails['option_group_id']);
312 if (!is_array($value)) {
313 $value = [$value];
314 }
315
316 $invalidOptions = array_diff($value, array_keys($options));
317 if (!empty($invalidOptions)) {
318 $errors[$fieldName] = "Invalid option(s) for field '{$fieldName}': " . implode(',', $invalidOptions);
319 }
320 }
321
322 return $errors;
323 }
324
325 /**
326 * CRM-15191 - Hack to ensure the cache gets cleared after updating a custom field.
327 *
328 * @param array $params
329 * Array per getfields metadata.
330 *
331 * @return array
332 */
333 function civicrm_api3_custom_field_setvalue($params) {
334 require_once 'api/v3/Generic/Setvalue.php';
335 $result = civicrm_api3_generic_setValue(["entity" => 'CustomField', 'params' => $params]);
336 if (empty($result['is_error'])) {
337 CRM_Utils_System::flushCache();
338 }
339 return $result;
340 }