Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-03-16-17-26-57
[civicrm-core.git] / api / v3 / Generic.php
1 <?php
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 */
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 * @return array
52 * API success object
53 */
54 function 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
59 CRM_Core_PseudoConstant::flush();
60 if (!empty($apiRequest['params']['fieldname'])) {
61 CRM_Utils_PseudoConstant::flushConstant($apiRequest['params']['fieldname']);
62 }
63 if (!empty($apiRequest['params']['option_group_id'])) {
64 $optionGroupName = civicrm_api('option_group', 'getvalue', array(
65 'version' => 3,
66 'id' => $apiRequest['params']['option_group_id'],
67 'return' => 'name',
68 ));
69 if (is_string($optionGroupName)) {
70 CRM_Utils_PseudoConstant::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
71 }
72 }
73 }
74 $entity = $apiRequest['entity'];
75 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
76 $subentity = CRM_Utils_Array::value('contact_type', $apiRequest['params']);
77 $action = CRM_Utils_Array::value('action', $apiRequest['params']);
78 $sequential = empty($apiRequest['params']) ? 0 : 1;
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());
81
82 if (!$action || $action == 'getvalue' || $action == 'getcount') {
83 $action = 'get';
84 }
85 // determines whether to use unique field names - see comment block above
86 $unique = TRUE;
87 // If no options, return results from cache
88 if (!$apiRequest['params']['options'] && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity])
89 && isset($action, $results[$entity . $subentity][$sequential])) {
90 return $results[$entity . $subentity][$action][$sequential];
91 }
92 // defaults based on data model and API policy
93 switch ($action) {
94 case 'getfields':
95 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
96 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
97
98 case 'create':
99 case 'update':
100 case 'replace':
101 $unique = FALSE;
102 case 'get':
103 case 'getsingle':
104 case 'getcount':
105 case 'getstat':
106 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
107 if (empty($metadata['id'])) {
108 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
109 if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
110 $metadata['id'] = $metadata[$lowercase_entity . '_id'];
111 unset($metadata[$lowercase_entity . '_id']);
112 $metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
113 }
114 }
115 else {
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
121 $metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
122 }
123 break;
124
125 case 'delete':
126 $metadata = array(
127 'id' => array(
128 'title' => $entity . ' ID',
129 'api.required' => 1,
130 'api.aliases' => array($lowercase_entity . '_id'),
131 'type' => CRM_Utils_Type::T_INT,
132 ));
133 break;
134
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':
138 $metadata = array(
139 'field' => array(
140 'title' => 'Field name',
141 'api.required' => 1,
142 'type' => CRM_Utils_Type::T_STRING,
143 ),
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,
153 ),
154 );
155 if (array_intersect(array('all', 'field'), $optionsToResolve)) {
156 $options = civicrm_api3_generic_getfields(array('entity' => $entity, array('params' => array('action' => 'create'))));
157 $metadata['field']['options'] = CRM_Utils_Array::collect('title', $options['values']);
158 }
159 break;
160
161 default:
162 // oddballs are on their own
163 $metadata = array();
164 }
165
166 // Normalize this for the sake of spec funcions
167 $apiRequest['params']['options']['get_options'] = $optionsToResolve;
168
169 // find any supplemental information
170 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
171 try {
172 list ($apiProvider, $hypApiRequest) = \Civi\Core\Container::singleton()->get('civi_api_kernel')->resolve($hypApiRequest);
173 if (isset($hypApiRequest['function'])) {
174 $helper = '_' . $hypApiRequest['function'] . '_spec';
175 }
176 else {
177 // not implemented MagicFunctionProvider
178 $helper = NULL;
179 }
180 }
181 catch (\Civi\API\Exception\NotImplementedException $e) {
182 $helper = NULL;
183 }
184 if (function_exists($helper)) {
185 // alter
186 $helper($metadata, $apiRequest);
187 }
188
189 foreach ($metadata as $fieldname => $fieldSpec) {
190 // Ensure 'name' is set
191 if (!isset($fieldSpec['name'])) {
192 $metadata[$fieldname]['name'] = $fieldname;
193 }
194 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec, $optionsToResolve);
195 // Convert options to "sequential" format
196 if (!empty($apiRequest['params']['sequential']) && !empty($metadata[$fieldname]['options'])) {
197 $metadata[$fieldname]['options'] = CRM_Utils_Array::makeNonAssociative($metadata[$fieldname]['options']);
198 }
199 }
200
201 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
202 return $results[$entity][$action][$sequential];
203 }
204
205 /**
206 * API return function to reformat results as count.
207 *
208 * @param array $apiRequest
209 * Api request as an array. Keys are.
210 *
211 * @throws API_Exception
212 * @return int
213 * count of results
214 */
215 function civicrm_api3_generic_getcount($apiRequest) {
216 $apiRequest['params']['options']['is_count'] = TRUE;
217 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
218 if (is_numeric(CRM_Utils_Array::value('values', $result))) {
219 return (int) $result['values'];
220 }
221 if (!isset($result['count'])) {
222 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
223 }
224 return $result['count'];
225 }
226
227 /**
228 * API return function to reformat results as single result.
229 *
230 * @param array $apiRequest
231 * Api request as an array. Keys are.
232 *
233 * @return int
234 * count of results
235 */
236 function civicrm_api3_generic_getsingle($apiRequest) {
237 // So the first entity is always result['values'][0].
238 $apiRequest['params']['sequential'] = 1;
239 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
240 if ($result['is_error'] !== 0) {
241 return $result;
242 }
243 if ($result['count'] === 1) {
244 return $result['values'][0];
245 }
246 if ($result['count'] !== 1) {
247 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
248 }
249 return civicrm_api3_create_error("Undefined behavior");
250 }
251
252 /**
253 * API return function to reformat results as single value.
254 *
255 * @param array $apiRequest
256 * Api request as an array. Keys are.
257 *
258 * @return int
259 * count of results
260 */
261 function civicrm_api3_generic_getvalue($apiRequest) {
262 $apiRequest['params']['sequential'] = 1;
263 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
264 if ($result['is_error'] !== 0) {
265 return $result;
266 }
267 if ($result['count'] !== 1) {
268 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
269 return $result;
270 }
271
272 // we only take "return=" as valid options
273 if (!empty($apiRequest['params']['return'])) {
274 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
275 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
276 }
277
278 return $result['values'][0][$apiRequest['params']['return']];
279 }
280
281 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
282 }
283
284 /**
285 * Get count of contact references.
286 *
287 * @param array $params
288 */
289 function _civicrm_api3_generic_getrefcount_spec(&$params, $apiRequest) {
290 $params['id']['api.required'] = 1;
291 $params['id']['title'] = $apiRequest['entity'] . ' ID';
292 $params['id']['type'] = CRM_Utils_Type::T_INT;
293 }
294
295 /**
296 * API to determine if a record is in-use.
297 *
298 * @param array $apiRequest
299 * Api request as an array.
300 *
301 * @throws API_Exception
302 * @return array
303 * API result (int 0 or 1)
304 */
305 function civicrm_api3_generic_getrefcount($apiRequest) {
306 $entityToClassMap = CRM_Core_DAO_AllCoreTables::daoToClass();
307 if (!isset($entityToClassMap[$apiRequest['entity']])) {
308 throw new API_Exception("The entity '{$apiRequest['entity']}' is unknown or unsupported by 'getrefcount'. Consider implementing this API.", 'getrefcount_unsupported');
309 }
310 $daoClass = $entityToClassMap[$apiRequest['entity']];
311
312 /* @var $dao CRM_Core_DAO */
313 $dao = new $daoClass();
314 $dao->id = $apiRequest['params']['id'];
315 if ($dao->find(TRUE)) {
316 return civicrm_api3_create_success($dao->getReferenceCounts());
317 }
318 else {
319 return civicrm_api3_create_success(array());
320 }
321 }
322
323 /**
324 * API wrapper for replace function.
325 *
326 * @param array $apiRequest
327 * Api request as an array. Keys are.
328 *
329 * @return int
330 * count of results
331 */
332 function civicrm_api3_generic_replace($apiRequest) {
333 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
334 }
335
336 /**
337 * API wrapper for getoptions function.
338 *
339 * @param array $apiRequest
340 * Api request as an array.
341 *
342 * @return array
343 * Array of results
344 */
345 function civicrm_api3_generic_getoptions($apiRequest) {
346 // Resolve aliases.
347 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
348 if (!$fieldName) {
349 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
350 }
351 // Validate 'context' from params
352 $context = CRM_Utils_Array::value('context', $apiRequest['params']);
353 CRM_Core_DAO::buildOptionsContext($context);
354 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
355
356 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
357 $options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
358 if ($options === FALSE) {
359 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
360 }
361 // Support 'sequential' output as a non-associative array
362 if (!empty($apiRequest['params']['sequential'])) {
363 $options = CRM_Utils_Array::makeNonAssociative($options);
364 }
365 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
366 }
367
368 /**
369 * Provide metadata for this generic action
370 *
371 * @param $params
372 * @param $apiRequest
373 */
374 function _civicrm_api3_generic_getoptions_spec(&$params, $apiRequest) {
375 $params += array(
376 'field' => array(
377 'title' => 'Field name',
378 'api.required' => 1,
379 'type' => CRM_Utils_Type::T_STRING,
380 ),
381 'context' => array(
382 'title' => 'Context',
383 'type' => CRM_Utils_Type::T_STRING,
384 ),
385 );
386
387 // Add available options to these params if requested
388 if (array_intersect(array('all', 'context'), $apiRequest['params']['options']['get_options'])) {
389 $params['context']['options'] = array_combine(array_keys(CRM_Core_DAO::buildOptionsContext()), array_keys(CRM_Core_DAO::buildOptionsContext()));
390 }
391 if (array_intersect(array('all', 'field'), $apiRequest['params']['options']['get_options'])) {
392 $fields = civicrm_api3_generic_getfields(array('entity' => $apiRequest['entity'], array('params' => array('action' => 'create'))));
393 $params['field']['options'] = array();
394 foreach ($fields['values'] as $name => $field) {
395 if (isset($field['pseudoconstant']) || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_BOOLEAN) {
396 $params['field']['options'][$name] = CRM_Utils_Array::value('title', $field, $name);
397 }
398 }
399 }
400 }
401
402 /**
403 * Get metadata.
404 *
405 * Function fills the 'options' array on the metadata returned by getfields if
406 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
407 * (this is passed in as the $fieldsToResolve array)
408 * 2) the field is a pseudoconstant and is NOT an FK
409 * - the reason for this is that checking / transformation is done on pseudoconstants but
410 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
411 * @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
412 *
413 * This function is only split out for the purpose of code clarity / comment block documentation
414 *
415 * @param array $metadata
416 * The array of metadata that will form the result of the getfields function.
417 * @param array $apiRequest
418 * @param string $fieldname
419 * Field currently being processed.
420 * @param array $fieldSpec
421 * Metadata for that field.
422 * @param array $fieldsToResolve
423 * Any field resolutions specifically requested.
424 */
425 function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve) {
426 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
427 return;
428 }
429
430 if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
431 return;
432 }
433
434 $options = civicrm_api($apiRequest['entity'], 'getoptions', array('version' => 3, 'field' => $fieldname));
435 if (is_array(CRM_Utils_Array::value('values', $options))) {
436 $metadata[$fieldname]['options'] = $options['values'];
437 }
438 }