Merge pull request #5503 from civicrm/4.6
[civicrm-core.git] / api / v3 / Generic.php
CommitLineData
6a488035 1<?php
b081365f
CW
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 */
6a488035
TO
31
32/**
61fe4988
EM
33 * Get information about fields for a given api request.
34 *
35 * Getfields information is used for documentation, validation, default setting
6a488035
TO
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 *
cf470720
TO
43 * @param array $apiRequest
44 * Api request as an array. Keys are.
16b10e64
CW
45 * - entity: string
46 * - action: string
47 * - version: string
48 * - function: callback (mixed)
49 * - params: array, varies
9d32e6f7 50 *
a6c01b45 51 * @return array
72b3a70c 52 * API success object
6a488035
TO
53 */
54function civicrm_api3_generic_getfields($apiRequest) {
55 static $results = array();
56 if ((CRM_Utils_Array::value('cache_clear', $apiRequest['params']))) {
57 $results = array();
58 // we will also clear pseudoconstants here - should potentially be moved to relevant BAO classes
37547b77 59 CRM_Core_PseudoConstant::flush();
9b873358 60 if (!empty($apiRequest['params']['fieldname'])) {
6a488035
TO
61 CRM_Utils_PseudoConstant::flushConstant($apiRequest['params']['fieldname']);
62 }
9b873358 63 if (!empty($apiRequest['params']['option_group_id'])) {
9d32e6f7
EM
64 $optionGroupName = civicrm_api('option_group', 'getvalue', array(
65 'version' => 3,
66 'id' => $apiRequest['params']['option_group_id'],
67 'return' => 'name',
68 ));
9b873358 69 if (is_string($optionGroupName)) {
6a488035
TO
70 CRM_Utils_PseudoConstant::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
71 }
72 }
73 }
4846df91
CW
74 $entity = $apiRequest['entity'];
75 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
6a488035 76 $subentity = CRM_Utils_Array::value('contact_type', $apiRequest['params']);
4846df91 77 $action = CRM_Utils_Array::value('action', $apiRequest['params']);
fce45a2f 78 $sequential = empty($apiRequest['params']['sequential']) ? 0 : 1;
2ce25e93
CW
79 $apiRequest['params']['options'] = CRM_Utils_Array::value('options', $apiRequest['params'], array());
80 $optionsToResolve = (array) CRM_Utils_Array::value('get_options', $apiRequest['params']['options'], array());
acadf548 81
54df0f0c 82 if (!$action || $action == 'getvalue' || $action == 'getcount') {
6a488035
TO
83 $action = 'get';
84 }
f7b2fef0 85 // determines whether to use unique field names - see comment block above
6a488035 86 $unique = TRUE;
2ce25e93
CW
87 // If no options, return results from cache
88 if (!$apiRequest['params']['options'] && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity])
ceccbc35 89 && isset($action, $results[$entity . $subentity][$sequential])) {
90 return $results[$entity . $subentity][$action][$sequential];
6a488035
TO
91 }
92 // defaults based on data model and API policy
93 switch ($action) {
94 case 'getfields':
9c8096cb 95 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
f2b53f26 96 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
ea100cb5 97
6a488035
TO
98 case 'create':
99 case 'update':
100 case 'replace':
101 $unique = FALSE;
102 case 'get':
2b6e1174
CW
103 case 'getsingle':
104 case 'getcount':
9c32b8f6 105 case 'getstat':
6a488035 106 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
9b873358 107 if (empty($metadata['id'])) {
9ec90e57 108 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
22e263ad 109 if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
4846df91
CW
110 $metadata['id'] = $metadata[$lowercase_entity . '_id'];
111 unset($metadata[$lowercase_entity . '_id']);
112 $metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
9ec90e57 113 }
114 }
92e4c2a5 115 else {
9ec90e57 116 // really the preference would be to set the unique name in the xml
117 // question is which is a less risky fix this close to a release - setting in xml for the known failure
118 // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
119 // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
120 // inconsistency
4846df91 121 $metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
6a488035
TO
122 }
123 break;
124
125 case 'delete':
126 $metadata = array(
3a8e9315
CW
127 'id' => array(
128 'title' => $entity . ' ID',
6a488035 129 'api.required' => 1,
4846df91 130 'api.aliases' => array($lowercase_entity . '_id'),
b2402735 131 'type' => CRM_Utils_Type::T_INT,
6a488035
TO
132 ));
133 break;
134
f7b2fef0
CW
135 // Note: adding setvalue case here instead of in a generic spec function because
136 // some APIs override the generic setvalue fn which causes the generic spec to be overlooked.
137 case 'setvalue':
6a488035 138 $metadata = array(
786ad6e1 139 'field' => array(
3a8e9315 140 'title' => 'Field name',
786ad6e1 141 'api.required' => 1,
f7b2fef0 142 'type' => CRM_Utils_Type::T_STRING,
786ad6e1 143 ),
f7b2fef0
CW
144 'id' => array(
145 'title' => $entity . ' ID',
146 'api.required' => 1,
147 'type' => CRM_Utils_Type::T_INT,
148 ),
149 'value' => array(
150 'title' => 'Value',
151 'description' => "Field value to set",
152 'api.required' => 1,
786ad6e1
CW
153 ),
154 );
acadf548
CW
155 if (array_intersect(array('all', 'field'), $optionsToResolve)) {
156 $options = civicrm_api3_generic_getfields(array('entity' => $entity, array('params' => array('action' => 'create'))));
2ce25e93 157 $metadata['field']['options'] = CRM_Utils_Array::collect('title', $options['values']);
acadf548 158 }
c866eb5f
TO
159 break;
160
6a488035
TO
161 default:
162 // oddballs are on their own
163 $metadata = array();
164 }
165
2ce25e93
CW
166 // Normalize this for the sake of spec funcions
167 $apiRequest['params']['options']['get_options'] = $optionsToResolve;
168
6a488035
TO
169 // find any supplemental information
170 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
c65db512
TO
171 try {
172 list ($apiProvider, $hypApiRequest) = \Civi\Core\Container::singleton()->get('civi_api_kernel')->resolve($hypApiRequest);
378e2654
TO
173 if (isset($hypApiRequest['function'])) {
174 $helper = '_' . $hypApiRequest['function'] . '_spec';
0db6c3e1
TO
175 }
176 else {
378e2654
TO
177 // not implemented MagicFunctionProvider
178 $helper = NULL;
179 }
0db6c3e1
TO
180 }
181 catch (\Civi\API\Exception\NotImplementedException $e) {
c65db512
TO
182 $helper = NULL;
183 }
6a488035
TO
184 if (function_exists($helper)) {
185 // alter
6a386447 186 $helper($metadata, $apiRequest);
6a488035
TO
187 }
188
6a488035 189 foreach ($metadata as $fieldname => $fieldSpec) {
a419926d
CW
190 // Ensure 'name' is set
191 if (!isset($fieldSpec['name'])) {
192 $metadata[$fieldname]['name'] = $fieldname;
193 }
acadf548 194 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec, $optionsToResolve);
fce45a2f 195
2ce25e93 196 // Convert options to "sequential" format
fce45a2f 197 if ($sequential && !empty($metadata[$fieldname]['options'])) {
2ce25e93
CW
198 $metadata[$fieldname]['options'] = CRM_Utils_Array::makeNonAssociative($metadata[$fieldname]['options']);
199 }
6a488035
TO
200 }
201
a14e9d08 202 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
ceccbc35 203 return $results[$entity][$action][$sequential];
6a488035
TO
204}
205
206/**
9d32e6f7 207 * API return function to reformat results as count.
6a488035 208 *
cf470720
TO
209 * @param array $apiRequest
210 * Api request as an array. Keys are.
6a488035 211 *
77b97be7 212 * @throws API_Exception
df8d3074 213 * @return int
72b3a70c 214 * count of results
6a488035
TO
215 */
216function civicrm_api3_generic_getcount($apiRequest) {
972322c5 217 $apiRequest['params']['options']['is_count'] = TRUE;
6a488035 218 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
37fa58b0 219 if (is_numeric(CRM_Utils_Array::value('values', $result))) {
972322c5 220 return (int) $result['values'];
221 }
22e263ad 222 if (!isset($result['count'])) {
8335b10a 223 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
224 }
6a488035
TO
225 return $result['count'];
226}
227
228/**
9d32e6f7 229 * API return function to reformat results as single result.
6a488035 230 *
cf470720
TO
231 * @param array $apiRequest
232 * Api request as an array. Keys are.
6a488035 233 *
df8d3074 234 * @return int
72b3a70c 235 * count of results
6a488035
TO
236 */
237function civicrm_api3_generic_getsingle($apiRequest) {
9d32e6f7 238 // So the first entity is always result['values'][0].
6a488035
TO
239 $apiRequest['params']['sequential'] = 1;
240 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
241 if ($result['is_error'] !== 0) {
242 return $result;
243 }
244 if ($result['count'] === 1) {
245 return $result['values'][0];
246 }
247 if ($result['count'] !== 1) {
248 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
249 }
250 return civicrm_api3_create_error("Undefined behavior");
251}
252
253/**
9d32e6f7 254 * API return function to reformat results as single value.
6a488035 255 *
cf470720
TO
256 * @param array $apiRequest
257 * Api request as an array. Keys are.
6a488035 258 *
df8d3074 259 * @return int
72b3a70c 260 * count of results
6a488035
TO
261 */
262function civicrm_api3_generic_getvalue($apiRequest) {
263 $apiRequest['params']['sequential'] = 1;
264 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
265 if ($result['is_error'] !== 0) {
266 return $result;
267 }
268 if ($result['count'] !== 1) {
269 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
270 return $result;
271 }
272
273 // we only take "return=" as valid options
a7488080 274 if (!empty($apiRequest['params']['return'])) {
6a488035
TO
275 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
276 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
277 }
278
279 return $result['values'][0][$apiRequest['params']['return']];
280 }
281
282 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
283}
284
4e87860d 285/**
9d32e6f7
EM
286 * Get count of contact references.
287 *
c490a46a 288 * @param array $params
4e87860d 289 */
5050d5d4 290function _civicrm_api3_generic_getrefcount_spec(&$params, $apiRequest) {
9c8096cb 291 $params['id']['api.required'] = 1;
5050d5d4
CW
292 $params['id']['title'] = $apiRequest['entity'] . ' ID';
293 $params['id']['type'] = CRM_Utils_Type::T_INT;
9c8096cb
TO
294}
295
296/**
9d32e6f7 297 * API to determine if a record is in-use.
9c8096cb 298 *
cf470720
TO
299 * @param array $apiRequest
300 * Api request as an array.
9c8096cb
TO
301 *
302 * @throws API_Exception
a6c01b45 303 * @return array
72b3a70c 304 * API result (int 0 or 1)
9c8096cb
TO
305 */
306function civicrm_api3_generic_getrefcount($apiRequest) {
307 $entityToClassMap = CRM_Core_DAO_AllCoreTables::daoToClass();
308 if (!isset($entityToClassMap[$apiRequest['entity']])) {
309 throw new API_Exception("The entity '{$apiRequest['entity']}' is unknown or unsupported by 'getrefcount'. Consider implementing this API.", 'getrefcount_unsupported');
310 }
311 $daoClass = $entityToClassMap[$apiRequest['entity']];
312
313 /* @var $dao CRM_Core_DAO */
314 $dao = new $daoClass();
315 $dao->id = $apiRequest['params']['id'];
316 if ($dao->find(TRUE)) {
317 return civicrm_api3_create_success($dao->getReferenceCounts());
318 }
319 else {
320 return civicrm_api3_create_success(array());
321 }
322}
323
6a488035 324/**
9d32e6f7 325 * API wrapper for replace function.
6a488035 326 *
cf470720
TO
327 * @param array $apiRequest
328 * Api request as an array. Keys are.
6a488035 329 *
df8d3074 330 * @return int
72b3a70c 331 * count of results
6a488035
TO
332 */
333function civicrm_api3_generic_replace($apiRequest) {
334 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
335}
336
337/**
9d32e6f7 338 * API wrapper for getoptions function.
6a488035 339 *
cf470720
TO
340 * @param array $apiRequest
341 * Api request as an array.
6a488035 342 *
a6c01b45 343 * @return array
16b10e64 344 * Array of results
6a488035
TO
345 */
346function civicrm_api3_generic_getoptions($apiRequest) {
9d32e6f7 347 // Resolve aliases.
70f7ba9e
CW
348 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
349 if (!$fieldName) {
350 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
351 }
a4a33486 352 // Validate 'context' from params
786ad6e1
CW
353 $context = CRM_Utils_Array::value('context', $apiRequest['params']);
354 CRM_Core_DAO::buildOptionsContext($context);
a3d8b390 355 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
70f7ba9e 356
786ad6e1 357 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
b7ceb253 358 $options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
ee2b1c1c 359 if ($options === FALSE) {
70f7ba9e 360 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
6a488035 361 }
15a1171a
CW
362 // Support 'sequential' output as a non-associative array
363 if (!empty($apiRequest['params']['sequential'])) {
b7ceb253 364 $options = CRM_Utils_Array::makeNonAssociative($options);
15a1171a 365 }
b7ceb253 366 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
6a488035
TO
367}
368
f7b2fef0
CW
369/**
370 * Provide metadata for this generic action
371 *
372 * @param $params
373 * @param $apiRequest
374 */
375function _civicrm_api3_generic_getoptions_spec(&$params, $apiRequest) {
f7b2fef0
CW
376 $params += array(
377 'field' => array(
378 'title' => 'Field name',
379 'api.required' => 1,
380 'type' => CRM_Utils_Type::T_STRING,
381 ),
382 'context' => array(
383 'title' => 'Context',
f7b2fef0
CW
384 'type' => CRM_Utils_Type::T_STRING,
385 ),
386 );
acadf548 387
acadf548 388 // Add available options to these params if requested
2ce25e93
CW
389 if (array_intersect(array('all', 'context'), $apiRequest['params']['options']['get_options'])) {
390 $params['context']['options'] = array_combine(array_keys(CRM_Core_DAO::buildOptionsContext()), array_keys(CRM_Core_DAO::buildOptionsContext()));
acadf548 391 }
2ce25e93 392 if (array_intersect(array('all', 'field'), $apiRequest['params']['options']['get_options'])) {
acadf548 393 $fields = civicrm_api3_generic_getfields(array('entity' => $apiRequest['entity'], array('params' => array('action' => 'create'))));
2ce25e93 394 $params['field']['options'] = array();
acadf548
CW
395 foreach ($fields['values'] as $name => $field) {
396 if (isset($field['pseudoconstant']) || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_BOOLEAN) {
2ce25e93 397 $params['field']['options'][$name] = CRM_Utils_Array::value('title', $field, $name);
acadf548
CW
398 }
399 }
acadf548 400 }
f7b2fef0
CW
401}
402
11e09c59 403/**
dc64d047
EM
404 * Get metadata.
405 *
6a488035
TO
406 * Function fills the 'options' array on the metadata returned by getfields if
407 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
408 * (this is passed in as the $fieldsToResolve array)
409 * 2) the field is a pseudoconstant and is NOT an FK
410 * - the reason for this is that checking / transformation is done on pseudoconstants but
411 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
7c285037 412 * @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
6a488035
TO
413 *
414 * This function is only split out for the purpose of code clarity / comment block documentation
77b97be7 415 *
cf470720
TO
416 * @param array $metadata
417 * The array of metadata that will form the result of the getfields function.
72b3a70c 418 * @param array $apiRequest
cf470720
TO
419 * @param string $fieldname
420 * Field currently being processed.
421 * @param array $fieldSpec
422 * Metadata for that field.
423 * @param array $fieldsToResolve
acadf548 424 * Any field resolutions specifically requested.
6a488035 425 */
9b873358 426function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve) {
3a8e9315 427 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
6a488035
TO
428 return;
429 }
430
ed8abbbb 431 if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
70f7ba9e
CW
432 return;
433 }
434
2ce25e93 435 $options = civicrm_api($apiRequest['entity'], 'getoptions', array('version' => 3, 'field' => $fieldname));
6a488035
TO
436 if (is_array(CRM_Utils_Array::value('values', $options))) {
437 $metadata[$fieldname]['options'] = $options['values'];
438 }
439}