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