Add in Wrapper template around DatePickerRange template to have better layout of...
[civicrm-core.git] / api / v3 / Generic.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * @package CiviCRM_APIv3
30 */
31
32 /**
33 * Get information about fields for a given api request.
34 *
35 * Getfields information is used for documentation, validation, default setting
36 * We first query the scheme using the $dao->fields function & then augment
37 * that information by calling the _spec functions that apply to the relevant function
38 * Note that we use 'unique' field names as described in the xml/schema files
39 * for get requests & just field name for create. This is because some get functions
40 * access multiple objects e.g. contact api accesses is_deleted from the activity
41 * table & from the contact table
42 *
43 * @param array $apiRequest
44 * Api request as an array. Keys are.
45 * - entity: string
46 * - action: string
47 * - version: string
48 * - function: callback (mixed)
49 * - params: array, varies
50 *
51 * @param bool $unique
52 * Determines whether to key by unique field names (only affects get-type) actions
53 *
54 * @return array
55 * API success object
56 */
57 function civicrm_api3_generic_getfields($apiRequest, $unique = TRUE) {
58 static $results = [];
59 if ((CRM_Utils_Array::value('cache_clear', $apiRequest['params']))) {
60 $results = [];
61 // we will also clear pseudoconstants here - should potentially be moved to relevant BAO classes
62 CRM_Core_PseudoConstant::flush();
63 if (!empty($apiRequest['params']['fieldname'])) {
64 CRM_Utils_PseudoConstant::flushConstant($apiRequest['params']['fieldname']);
65 }
66 if (!empty($apiRequest['params']['option_group_id'])) {
67 $optionGroupName = civicrm_api('option_group', 'getvalue', [
68 'version' => 3,
69 'id' => $apiRequest['params']['option_group_id'],
70 'return' => 'name',
71 ]);
72 if (is_string($optionGroupName)) {
73 CRM_Utils_PseudoConstant::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
74 }
75 }
76 }
77 $entity = $apiRequest['entity'];
78 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
79 $subentity = CRM_Utils_Array::value('contact_type', $apiRequest['params']);
80 $action = CRM_Utils_Array::value('action', $apiRequest['params']);
81 $sequential = empty($apiRequest['params']['sequential']) ? 0 : 1;
82 $apiRequest['params']['options'] = CRM_Utils_Array::value('options', $apiRequest['params'], []);
83 $optionsToResolve = (array) CRM_Utils_Array::value('get_options', $apiRequest['params']['options'], []);
84
85 if (!$action || $action == 'getvalue' || $action == 'getcount') {
86 $action = 'get';
87 }
88 // If no options, return results from cache
89 if (!$apiRequest['params']['options'] && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity])
90 && isset($action, $results[$entity . $subentity][$sequential])) {
91 return $results[$entity . $subentity][$action][$sequential];
92 }
93 // defaults based on data model and API policy
94 switch ($action) {
95 case 'getfields':
96 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
97 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
98
99 case 'create':
100 case 'update':
101 case 'replace':
102 $unique = FALSE;
103 case 'get':
104 case 'getsingle':
105 case 'getcount':
106 case 'getstat':
107 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
108 if (empty($metadata['id'])) {
109 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
110 if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
111 $metadata['id'] = $metadata[$lowercase_entity . '_id'];
112 unset($metadata[$lowercase_entity . '_id']);
113 $metadata['id']['api.aliases'] = [$lowercase_entity . '_id'];
114 }
115 }
116 else {
117 // really the preference would be to set the unique name in the xml
118 // question is which is a less risky fix this close to a release - setting in xml for the known failure
119 // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
120 // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
121 // inconsistency
122 $metadata['id']['api.aliases'] = [$lowercase_entity . '_id'];
123 }
124 break;
125
126 case 'delete':
127 $metadata = [
128 'id' => [
129 'title' => $entity . ' ID',
130 'api.required' => 1,
131 'api.aliases' => [$lowercase_entity . '_id'],
132 'type' => CRM_Utils_Type::T_INT,
133 ],
134 ];
135 break;
136
137 // Note: adding setvalue case here instead of in a generic spec function because
138 // some APIs override the generic setvalue fn which causes the generic spec to be overlooked.
139 case 'setvalue':
140 $metadata = [
141 'field' => [
142 'title' => 'Field name',
143 'api.required' => 1,
144 'type' => CRM_Utils_Type::T_STRING,
145 ],
146 'id' => [
147 'title' => $entity . ' ID',
148 'api.required' => 1,
149 'type' => CRM_Utils_Type::T_INT,
150 ],
151 'value' => [
152 'title' => 'Value',
153 'description' => "Field value to set",
154 'api.required' => 1,
155 ],
156 ];
157 if (array_intersect(['all', 'field'], $optionsToResolve)) {
158 $options = civicrm_api3_generic_getfields(['entity' => $entity, ['params' => ['action' => 'create']]]);
159 $metadata['field']['options'] = CRM_Utils_Array::collect('title', $options['values']);
160 }
161 break;
162
163 default:
164 // oddballs are on their own
165 $metadata = [];
166 }
167
168 // Hack for product api to pass tests.
169 if (!is_string($apiRequest['params']['options'])) {
170 // Normalize this for the sake of spec funcions
171 $apiRequest['params']['options']['get_options'] = $optionsToResolve;
172 }
173
174 // find any supplemental information
175 $hypApiRequest = ['entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']];
176 if ($action == 'getsingle') {
177 $hypApiRequest['action'] = 'get';
178 }
179 try {
180 list ($apiProvider, $hypApiRequest) = \Civi::service('civi_api_kernel')->resolve($hypApiRequest);
181 if (isset($hypApiRequest['function'])) {
182 $helper = '_' . $hypApiRequest['function'] . '_spec';
183 }
184 else {
185 // not implemented MagicFunctionProvider
186 $helper = NULL;
187 }
188 }
189 catch (\Civi\API\Exception\NotImplementedException $e) {
190 $helper = NULL;
191 }
192 if (function_exists($helper)) {
193 // alter
194 $helper($metadata, $apiRequest);
195 }
196
197 foreach ($metadata as $fieldname => $fieldSpec) {
198 // Ensure 'name' is set
199 if (!isset($fieldSpec['name'])) {
200 $metadata[$fieldname]['name'] = $fieldname;
201 }
202 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec);
203
204 // Convert options to "sequential" format
205 if ($sequential && !empty($metadata[$fieldname]['options'])) {
206 $metadata[$fieldname]['options'] = CRM_Utils_Array::makeNonAssociative($metadata[$fieldname]['options']);
207 }
208 }
209
210 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
211 return $results[$entity][$action][$sequential];
212 }
213
214 /**
215 * Get metadata for a field
216 *
217 * @param array $apiRequest
218 *
219 * @return array
220 * API success object
221 */
222 function civicrm_api3_generic_getfield($apiRequest) {
223 $params = $apiRequest['params'];
224 $sequential = !empty($params['sequential']);
225 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $params['name'], $params['action']);
226 if (!$fieldName) {
227 return civicrm_api3_create_error("The field '{$params['name']}' doesn't exist.");
228 }
229 // Turn off sequential to make the field easier to find
230 $apiRequest['params']['sequential'] = 0;
231 if (isset($params['get_options'])) {
232 $apiRequest['params']['options']['get_options_context'] = $params['get_options'];
233 $apiRequest['params']['options']['get_options'] = $fieldName;
234 }
235 $result = civicrm_api3_generic_getfields($apiRequest, FALSE);
236 $result = $result['values'][$fieldName];
237 // Fix sequential options since we forced it off
238 if ($sequential && !empty($result['options'])) {
239 $result['options'] = CRM_Utils_Array::makeNonAssociative($result['options']);
240 }
241 return civicrm_api3_create_success($result, $apiRequest['params'], $apiRequest['entity'], 'getfield');
242 }
243
244 /**
245 * Get metadata for getfield action.
246 *
247 * @param array $params
248 * @param array $apiRequest
249 *
250 * @throws \CiviCRM_API3_Exception
251 * @throws \Exception
252 */
253 function _civicrm_api3_generic_getfield_spec(&$params, $apiRequest) {
254 $params = [
255 'name' => [
256 'title' => 'Field name',
257 'description' => 'Name or alias of field to lookup',
258 'api.required' => 1,
259 'type' => CRM_Utils_Type::T_STRING,
260 ],
261 'action' => [
262 'title' => 'API Action',
263 'api.required' => 1,
264 'type' => CRM_Utils_Type::T_STRING,
265 'api.aliases' => ['api_action'],
266 ],
267 'get_options' => [
268 'title' => 'Get Options',
269 'description' => 'Context for which to get field options, or null to skip fetching options.',
270 'type' => CRM_Utils_Type::T_STRING,
271 'options' => CRM_Core_DAO::buildOptionsContext(),
272 'api.aliases' => ['context'],
273 ],
274 ];
275 // Add available options to these params if requested
276 if (array_intersect(['all', 'action'], $apiRequest['params']['options']['get_options'])) {
277 $actions = civicrm_api3($apiRequest['entity'], 'getactions');
278 $actions = array_combine($actions['values'], $actions['values']);
279 // Let's not go meta-crazy
280 CRM_Utils_Array::remove($actions, 'getactions', 'getoptions', 'getfields', 'getfield', 'getcount', 'getrefcount', 'getsingle', 'getlist', 'getvalue', 'setvalue', 'update');
281 $params['action']['options'] = $actions;
282 }
283 }
284
285 /**
286 * API return function to reformat results as count.
287 *
288 * @param array $apiRequest
289 * Api request as an array. Keys are.
290 *
291 * @throws API_Exception
292 * @return int
293 * count of results
294 */
295 function civicrm_api3_generic_getcount($apiRequest) {
296 $apiRequest['params']['options']['is_count'] = TRUE;
297 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
298 if (is_numeric(CRM_Utils_Array::value('values', $result))) {
299 return (int) $result['values'];
300 }
301 if (!isset($result['count'])) {
302 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
303 }
304 return $result['count'];
305 }
306
307 /**
308 * API return function to reformat results as single result.
309 *
310 * @param array $apiRequest
311 * Api request as an array. Keys are.
312 *
313 * @return int
314 * count of results
315 */
316 function civicrm_api3_generic_getsingle($apiRequest) {
317 // So the first entity is always result['values'][0].
318 $apiRequest['params']['sequential'] = 1;
319 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
320 if ($result['is_error'] !== 0) {
321 return $result;
322 }
323 if ($result['count'] === 1) {
324 return $result['values'][0];
325 }
326 if ($result['count'] !== 1) {
327 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], ['count' => $result['count']]);
328 }
329 return civicrm_api3_create_error("Undefined behavior");
330 }
331
332 /**
333 * API return function to reformat results as single value.
334 *
335 * @param array $apiRequest
336 * Api request as an array. Keys are.
337 *
338 * @return int
339 * count of results
340 */
341 function civicrm_api3_generic_getvalue($apiRequest) {
342 $apiRequest['params']['sequential'] = 1;
343 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
344 if ($result['is_error'] !== 0) {
345 return $result;
346 }
347 if ($result['count'] !== 1) {
348 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], ['count' => $result['count']]);
349 return $result;
350 }
351
352 // we only take "return=" as valid options
353 if (!empty($apiRequest['params']['return'])) {
354 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
355 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", ['invalid_field' => $apiRequest['params']['return']]);
356 }
357
358 return $result['values'][0][$apiRequest['params']['return']];
359 }
360
361 return civicrm_api3_create_error("missing param return=field you want to read the value of", ['error_type' => 'mandatory_missing', 'missing_param' => 'return']);
362 }
363
364 /**
365 * Get count of contact references.
366 *
367 * @param array $params
368 * @param array $apiRequest
369 */
370 function _civicrm_api3_generic_getrefcount_spec(&$params, $apiRequest) {
371 $params['id']['api.required'] = 1;
372 $params['id']['title'] = $apiRequest['entity'] . ' ID';
373 $params['id']['type'] = CRM_Utils_Type::T_INT;
374 }
375
376 /**
377 * API to determine if a record is in-use.
378 *
379 * @param array $apiRequest
380 * Api request as an array.
381 *
382 * @throws API_Exception
383 * @return array
384 * API result (int 0 or 1)
385 */
386 function civicrm_api3_generic_getrefcount($apiRequest) {
387 $entityToClassMap = CRM_Core_DAO_AllCoreTables::daoToClass();
388 if (!isset($entityToClassMap[$apiRequest['entity']])) {
389 throw new API_Exception("The entity '{$apiRequest['entity']}' is unknown or unsupported by 'getrefcount'. Consider implementing this API.", 'getrefcount_unsupported');
390 }
391 $daoClass = $entityToClassMap[$apiRequest['entity']];
392
393 /* @var $dao CRM_Core_DAO */
394 $dao = new $daoClass();
395 $dao->id = $apiRequest['params']['id'];
396 if ($dao->find(TRUE)) {
397 return civicrm_api3_create_success($dao->getReferenceCounts());
398 }
399 else {
400 return civicrm_api3_create_success([]);
401 }
402 }
403
404 /**
405 * API wrapper for replace function.
406 *
407 * @param array $apiRequest
408 * Api request as an array. Keys are.
409 *
410 * @return int
411 * count of results
412 */
413 function civicrm_api3_generic_replace($apiRequest) {
414 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
415 }
416
417 /**
418 * API wrapper for getoptions function.
419 *
420 * @param array $apiRequest
421 * Api request as an array.
422 *
423 * @return array
424 * Array of results
425 */
426 function civicrm_api3_generic_getoptions($apiRequest) {
427 // Resolve aliases.
428 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
429 if (!$fieldName) {
430 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
431 }
432 // Validate 'context' from params
433 $context = CRM_Utils_Array::value('context', $apiRequest['params']);
434 CRM_Core_DAO::buildOptionsContext($context);
435 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
436
437 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
438 $options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
439 if ($options === FALSE) {
440 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
441 }
442 // Support 'sequential' output as a non-associative array
443 if (!empty($apiRequest['params']['sequential'])) {
444 $options = CRM_Utils_Array::makeNonAssociative($options);
445 }
446 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
447 }
448
449 /**
450 * Provide metadata for this generic action
451 *
452 * @param $params
453 * @param $apiRequest
454 */
455 function _civicrm_api3_generic_getoptions_spec(&$params, $apiRequest) {
456 $params += [
457 'field' => [
458 'title' => 'Field name',
459 'api.required' => 1,
460 'type' => CRM_Utils_Type::T_STRING,
461 ],
462 'context' => [
463 'title' => 'Context',
464 'type' => CRM_Utils_Type::T_STRING,
465 'options' => CRM_Core_DAO::buildOptionsContext(),
466 ],
467 ];
468
469 // Add available fields if requested
470 if (array_intersect(['all', 'field'], $apiRequest['params']['options']['get_options'])) {
471 $fields = civicrm_api3_generic_getfields(['entity' => $apiRequest['entity'], ['params' => ['action' => 'create']]]);
472 $params['field']['options'] = [];
473 foreach ($fields['values'] as $name => $field) {
474 if (isset($field['pseudoconstant']) || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_BOOLEAN) {
475 $params['field']['options'][$name] = CRM_Utils_Array::value('title', $field, $name);
476 }
477 }
478 }
479
480 $entityName = _civicrm_api_get_entity_name_from_camel($apiRequest['entity']);
481 $getOptionsSpecFunction = '_civicrm_api3_' . $entityName . '_getoptions_spec';
482
483 if (function_exists($getOptionsSpecFunction)) {
484 $getOptionsSpecFunction($params);
485 }
486 }
487
488 /**
489 * Get metadata.
490 *
491 * Function fills the 'options' array on the metadata returned by getfields if
492 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
493 * (this is passed in as the $fieldsToResolve array)
494 * 2) the field is a pseudoconstant and is NOT an FK
495 * - the reason for this is that checking / transformation is done on pseudoconstants but
496 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
497 * @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
498 *
499 * This function is only split out for the purpose of code clarity / comment block documentation
500 *
501 * @param array $metadata
502 * The array of metadata that will form the result of the getfields function.
503 * @param array $apiRequest
504 * @param string $fieldname
505 * Field currently being processed.
506 * @param array $fieldSpec
507 * Metadata for that field.
508 */
509 function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec) {
510 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
511 return;
512 }
513
514 $fieldsToResolve = $apiRequest['params']['options']['get_options'];
515
516 if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
517 return;
518 }
519
520 // Allow caller to specify context
521 $context = CRM_Utils_Array::value('get_options_context', $apiRequest['params']['options']);
522 // Default to api action if it is a supported context.
523 if (!$context) {
524 $action = CRM_Utils_Array::value('action', $apiRequest['params']);
525 $contexts = CRM_Core_DAO::buildOptionsContext();
526 if (isset($contexts[$action])) {
527 $context = $action;
528 }
529 }
530
531 $options = civicrm_api($apiRequest['entity'], 'getoptions', ['version' => 3, 'field' => $fieldname, 'context' => $context]);
532 if (is_array(CRM_Utils_Array::value('values', $options))) {
533 $metadata[$fieldname]['options'] = $options['values'];
534 }
535 }