Merge pull request #5242 from colemanw/getstat
[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']);
ceccbc35 78 $sequential = empty($apiRequest['params']) ? 0 : 1;
6a488035 79 $apiOptions = CRM_Utils_Array::value('options', $apiRequest['params'], array());
54df0f0c 80 if (!$action || $action == 'getvalue' || $action == 'getcount') {
6a488035
TO
81 $action = 'get';
82 }
6a488035
TO
83 // determines whether to use unique field names - seem comment block above
84 $unique = TRUE;
ceccbc35 85 if (empty($apiOptions) && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity])
86 && isset($action, $results[$entity . $subentity][$sequential])) {
87 return $results[$entity . $subentity][$action][$sequential];
6a488035
TO
88 }
89 // defaults based on data model and API policy
90 switch ($action) {
91 case 'getfields':
9c8096cb 92 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
f2b53f26 93 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
ea100cb5 94
6a488035
TO
95 case 'create':
96 case 'update':
97 case 'replace':
98 $unique = FALSE;
99 case 'get':
2b6e1174
CW
100 case 'getsingle':
101 case 'getcount':
9c32b8f6 102 case 'getstat':
6a488035 103 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
9b873358 104 if (empty($metadata['id'])) {
9ec90e57 105 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
22e263ad 106 if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
4846df91
CW
107 $metadata['id'] = $metadata[$lowercase_entity . '_id'];
108 unset($metadata[$lowercase_entity . '_id']);
109 $metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
9ec90e57 110 }
111 }
92e4c2a5 112 else {
9ec90e57 113 // really the preference would be to set the unique name in the xml
114 // question is which is a less risky fix this close to a release - setting in xml for the known failure
115 // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
116 // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
117 // inconsistency
4846df91 118 $metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
6a488035
TO
119 }
120 break;
121
122 case 'delete':
123 $metadata = array(
3a8e9315
CW
124 'id' => array(
125 'title' => $entity . ' ID',
126 'name' => 'id',
6a488035 127 'api.required' => 1,
4846df91 128 'api.aliases' => array($lowercase_entity . '_id'),
b2402735 129 'type' => CRM_Utils_Type::T_INT,
6a488035
TO
130 ));
131 break;
132
133 case 'getoptions':
134 $metadata = array(
786ad6e1 135 'field' => array(
3a8e9315
CW
136 'name' => 'field',
137 'title' => 'Field name',
786ad6e1
CW
138 'api.required' => 1,
139 ),
140 'context' => array(
3a8e9315
CW
141 'name' => 'context',
142 'title' => 'Context',
786ad6e1
CW
143 ),
144 );
c866eb5f
TO
145 break;
146
6a488035
TO
147 default:
148 // oddballs are on their own
149 $metadata = array();
150 }
151
152 // find any supplemental information
153 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
c65db512
TO
154 try {
155 list ($apiProvider, $hypApiRequest) = \Civi\Core\Container::singleton()->get('civi_api_kernel')->resolve($hypApiRequest);
378e2654
TO
156 if (isset($hypApiRequest['function'])) {
157 $helper = '_' . $hypApiRequest['function'] . '_spec';
0db6c3e1
TO
158 }
159 else {
378e2654
TO
160 // not implemented MagicFunctionProvider
161 $helper = NULL;
162 }
0db6c3e1
TO
163 }
164 catch (\Civi\API\Exception\NotImplementedException $e) {
c65db512
TO
165 $helper = NULL;
166 }
6a488035
TO
167 if (function_exists($helper)) {
168 // alter
6a386447 169 $helper($metadata, $apiRequest);
6a488035
TO
170 }
171
a4c5e9a3 172 $fieldsToResolve = (array) CRM_Utils_Array::value('get_options', $apiOptions, array());
6a488035
TO
173
174 foreach ($metadata as $fieldname => $fieldSpec) {
a419926d
CW
175 // Ensure 'name' is set
176 if (!isset($fieldSpec['name'])) {
177 $metadata[$fieldname]['name'] = $fieldname;
178 }
ddaac11c 179 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve);
6a488035
TO
180 }
181
a14e9d08 182 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
ceccbc35 183 return $results[$entity][$action][$sequential];
6a488035
TO
184}
185
186/**
9d32e6f7 187 * API return function to reformat results as count.
6a488035 188 *
cf470720
TO
189 * @param array $apiRequest
190 * Api request as an array. Keys are.
6a488035 191 *
77b97be7 192 * @throws API_Exception
df8d3074 193 * @return int
72b3a70c 194 * count of results
6a488035
TO
195 */
196function civicrm_api3_generic_getcount($apiRequest) {
972322c5 197 $apiRequest['params']['options']['is_count'] = TRUE;
6a488035 198 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
37fa58b0 199 if (is_numeric(CRM_Utils_Array::value('values', $result))) {
972322c5 200 return (int) $result['values'];
201 }
22e263ad 202 if (!isset($result['count'])) {
8335b10a 203 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
204 }
6a488035
TO
205 return $result['count'];
206}
207
208/**
9d32e6f7 209 * API return function to reformat results as single result.
6a488035 210 *
cf470720
TO
211 * @param array $apiRequest
212 * Api request as an array. Keys are.
6a488035 213 *
df8d3074 214 * @return int
72b3a70c 215 * count of results
6a488035
TO
216 */
217function civicrm_api3_generic_getsingle($apiRequest) {
9d32e6f7 218 // So the first entity is always result['values'][0].
6a488035
TO
219 $apiRequest['params']['sequential'] = 1;
220 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
221 if ($result['is_error'] !== 0) {
222 return $result;
223 }
224 if ($result['count'] === 1) {
225 return $result['values'][0];
226 }
227 if ($result['count'] !== 1) {
228 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
229 }
230 return civicrm_api3_create_error("Undefined behavior");
231}
232
233/**
9d32e6f7 234 * API return function to reformat results as single value.
6a488035 235 *
cf470720
TO
236 * @param array $apiRequest
237 * Api request as an array. Keys are.
6a488035 238 *
df8d3074 239 * @return int
72b3a70c 240 * count of results
6a488035
TO
241 */
242function civicrm_api3_generic_getvalue($apiRequest) {
243 $apiRequest['params']['sequential'] = 1;
244 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
245 if ($result['is_error'] !== 0) {
246 return $result;
247 }
248 if ($result['count'] !== 1) {
249 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
250 return $result;
251 }
252
253 // we only take "return=" as valid options
a7488080 254 if (!empty($apiRequest['params']['return'])) {
6a488035
TO
255 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
256 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
257 }
258
259 return $result['values'][0][$apiRequest['params']['return']];
260 }
261
262 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
263}
264
4e87860d 265/**
9d32e6f7
EM
266 * Get count of contact references.
267 *
c490a46a 268 * @param array $params
4e87860d 269 */
9c8096cb
TO
270function _civicrm_api3_generic_getrefcount_spec(&$params) {
271 $params['id']['api.required'] = 1;
4c41ecb2 272 $params['id']['title'] = 'Entity ID';
9c8096cb
TO
273}
274
275/**
9d32e6f7 276 * API to determine if a record is in-use.
9c8096cb 277 *
cf470720
TO
278 * @param array $apiRequest
279 * Api request as an array.
9c8096cb
TO
280 *
281 * @throws API_Exception
a6c01b45 282 * @return array
72b3a70c 283 * API result (int 0 or 1)
9c8096cb
TO
284 */
285function civicrm_api3_generic_getrefcount($apiRequest) {
286 $entityToClassMap = CRM_Core_DAO_AllCoreTables::daoToClass();
287 if (!isset($entityToClassMap[$apiRequest['entity']])) {
288 throw new API_Exception("The entity '{$apiRequest['entity']}' is unknown or unsupported by 'getrefcount'. Consider implementing this API.", 'getrefcount_unsupported');
289 }
290 $daoClass = $entityToClassMap[$apiRequest['entity']];
291
292 /* @var $dao CRM_Core_DAO */
293 $dao = new $daoClass();
294 $dao->id = $apiRequest['params']['id'];
295 if ($dao->find(TRUE)) {
296 return civicrm_api3_create_success($dao->getReferenceCounts());
297 }
298 else {
299 return civicrm_api3_create_success(array());
300 }
301}
302
6a488035 303/**
9d32e6f7 304 * API wrapper for replace function.
6a488035 305 *
cf470720
TO
306 * @param array $apiRequest
307 * Api request as an array. Keys are.
6a488035 308 *
df8d3074 309 * @return int
72b3a70c 310 * count of results
6a488035
TO
311 */
312function civicrm_api3_generic_replace($apiRequest) {
313 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
314}
315
316/**
9d32e6f7 317 * API wrapper for getoptions function.
6a488035 318 *
cf470720
TO
319 * @param array $apiRequest
320 * Api request as an array.
6a488035 321 *
a6c01b45 322 * @return array
16b10e64 323 * Array of results
6a488035
TO
324 */
325function civicrm_api3_generic_getoptions($apiRequest) {
9d32e6f7 326 // Resolve aliases.
70f7ba9e
CW
327 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
328 if (!$fieldName) {
329 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
330 }
a4a33486 331 // Validate 'context' from params
786ad6e1
CW
332 $context = CRM_Utils_Array::value('context', $apiRequest['params']);
333 CRM_Core_DAO::buildOptionsContext($context);
a3d8b390 334 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
70f7ba9e 335
786ad6e1 336 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
b7ceb253 337 $options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
ee2b1c1c 338 if ($options === FALSE) {
70f7ba9e 339 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
6a488035 340 }
15a1171a
CW
341 // Support 'sequential' output as a non-associative array
342 if (!empty($apiRequest['params']['sequential'])) {
b7ceb253 343 $options = CRM_Utils_Array::makeNonAssociative($options);
15a1171a 344 }
b7ceb253 345 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
6a488035
TO
346}
347
11e09c59 348/**
dc64d047
EM
349 * Get metadata.
350 *
6a488035
TO
351 * Function fills the 'options' array on the metadata returned by getfields if
352 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
353 * (this is passed in as the $fieldsToResolve array)
354 * 2) the field is a pseudoconstant and is NOT an FK
355 * - the reason for this is that checking / transformation is done on pseudoconstants but
356 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
7c285037 357 * @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
6a488035
TO
358 *
359 * This function is only split out for the purpose of code clarity / comment block documentation
77b97be7 360 *
cf470720
TO
361 * @param array $metadata
362 * The array of metadata that will form the result of the getfields function.
72b3a70c 363 * @param array $apiRequest
cf470720
TO
364 * @param string $fieldname
365 * Field currently being processed.
366 * @param array $fieldSpec
367 * Metadata for that field.
368 * @param array $fieldsToResolve
369 * Anny field resolutions specifically requested.
6a488035 370 */
9b873358 371function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve) {
3a8e9315 372 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
6a488035
TO
373 return;
374 }
375
ed8abbbb 376 if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
70f7ba9e
CW
377 return;
378 }
379
ddaac11c 380 $options = civicrm_api($apiRequest['entity'], 'getoptions', array('version' => 3, 'field' => $fieldname, 'sequential' => !empty($apiRequest['params']['sequential'])));
6a488035
TO
381 if (is_array(CRM_Utils_Array::value('values', $options))) {
382 $metadata[$fieldname]['options'] = $options['values'];
383 }
384}