Merge pull request #1534 from eileenmcnaughton/labels
[civicrm-core.git] / api / api.php
1 <?php
2
3 /**
4 * File for the CiviCRM APIv3 API wrapper
5 *
6 * @package CiviCRM_APIv3
7 * @subpackage API
8 *
9 * @copyright CiviCRM LLC (c) 2004-2013
10 * @version $Id: api.php 30486 2010-11-02 16:12:09Z shot $
11 */
12
13 /**
14 * @param string $entity
15 * type of entities to deal with
16 * @param string $action
17 * create, get, delete or some special action name.
18 * @param array $params
19 * array to be passed to function
20 */
21 function civicrm_api($entity, $action, $params, $extra = NULL) {
22 $apiRequest = array();
23 $apiRequest['entity'] = CRM_Utils_String::munge($entity);
24 $apiRequest['action'] = CRM_Utils_String::munge($action);
25 $apiRequest['version'] = civicrm_get_api_version($params);
26 $apiRequest['params'] = $params;
27 $apiRequest['extra'] = $extra;
28
29 $apiWrappers = array(
30 CRM_Utils_API_HTMLInputCoder::singleton(),
31 CRM_Utils_API_NullOutputCoder::singleton(),
32 CRM_Utils_API_ReloadOption::singleton(),
33 );
34 CRM_Utils_Hook::apiWrappers($apiWrappers,$apiRequest);
35
36 try {
37 require_once ('api/v3/utils.php');
38 require_once 'api/Exception.php';
39 if (!is_array($params)) {
40 throw new API_Exception('Input variable `params` is not an array', 2000);
41 }
42 _civicrm_api3_initialize();
43 $errorScope = CRM_Core_TemporaryErrorScope::useException();
44 // look up function, file, is_generic
45 $apiRequest += _civicrm_api_resolve($apiRequest);
46 if (strtolower($action) == 'create' || strtolower($action) == 'delete') {
47 $apiRequest['is_transactional'] = 1;
48 $transaction = new CRM_Core_Transaction();
49 }
50
51 // support multi-lingual requests
52 if ($language = CRM_Utils_Array::value('option.language', $params)) {
53 _civicrm_api_set_locale($language);
54 }
55
56 _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
57
58 // we do this before we
59 _civicrm_api3_swap_out_aliases($apiRequest);
60 if (strtolower($action) != 'getfields') {
61 if (!CRM_Utils_Array::value('id', $apiRequest['params'])) {
62 $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest), $apiRequest['params']);
63 }
64 //if 'id' is set then only 'version' will be checked but should still be checked for consistency
65 civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest));
66 }
67
68 // For input filtering, process $apiWrappers in forward order
69 foreach ($apiWrappers as $apiWrapper) {
70 $apiRequest = $apiWrapper->fromApiInput($apiRequest);
71 }
72
73 $function = $apiRequest['function'];
74 if ($apiRequest['function'] && $apiRequest['is_generic']) {
75 // Unlike normal API implementations, generic implementations require explicit
76 // knowledge of the entity and action (as well as $params). Bundle up these bits
77 // into a convenient data structure.
78 $result = $function($apiRequest);
79 }
80 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
81 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
82
83 $result = isset($extra) ? $function($apiRequest['params'], $extra) : $function($apiRequest['params']);
84 }
85 else {
86 return civicrm_api3_create_error("API (" . $apiRequest['entity'] . "," . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
87 }
88
89 // For output filtering, process $apiWrappers in reverse order
90 foreach (array_reverse($apiWrappers) as $apiWrapper) {
91 $result = $apiWrapper->toApiOutput($apiRequest, $result);
92 }
93
94 if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
95 if ($result['is_error'] === 0) {
96 return 1;
97 }
98 else {
99 return 0;
100 }
101 }
102 if (CRM_Utils_Array::value('format.only_id', $apiRequest['params']) && isset($result['id'])) {
103 return $result['id'];
104 }
105 if (CRM_Utils_Array::value('is_error', $result, 0) == 0) {
106 _civicrm_api_call_nested_api($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
107 }
108 if (function_exists('xdebug_time_index')
109 && CRM_Utils_Array::value('debug', $apiRequest['params'])
110 // result would not be an array for getvalue
111 && is_array($result)
112 ) {
113 $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
114 $result['xdebug']['memory'] = xdebug_memory_usage();
115 $result['xdebug']['timeIndex'] = xdebug_time_index();
116 }
117
118 return $result;
119 }
120 catch(PEAR_Exception $e) {
121 if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
122 return 0;
123 }
124 $error = $e->getCause();
125 if ($error instanceof DB_Error) {
126 $data["error_code"] = DB::errorMessage($error->getCode());
127 $data["sql"] = $error->getDebugInfo();
128 }
129 if (CRM_Utils_Array::value('debug', $apiRequest['params'])) {
130 if(method_exists($e, 'getUserInfo')) {
131 $data['debug_info'] = $error->getUserInfo();
132 }
133 if(method_exists($e, 'getExtraData')) {
134 $data['debug_info'] = $data + $error->getExtraData();
135 }
136 $data['trace'] = $e->getTraceAsString();
137 }
138 else{
139 $data['tip'] = "add debug=1 to your API call to have more info about the error";
140 }
141 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
142 if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
143 $transaction->rollback();
144 }
145 return $err;
146 }
147 catch (API_Exception $e){
148 if(!isset($apiRequest)){
149 $apiRequest = array();
150 }
151 if (CRM_Utils_Array::value('format.is_success', CRM_Utils_Array::value('params',$apiRequest)) == 1) {
152 return 0;
153 }
154 $data = $e->getExtraParams();
155 $data['entity'] = CRM_Utils_Array::value('entity', $apiRequest);
156 $data['action'] = CRM_Utils_Array::value('action', $apiRequest);
157 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
158 if (CRM_Utils_Array::value('debug', CRM_Utils_Array::value('params',$apiRequest))
159 && empty($data['trace']) // prevent recursion
160 ) {
161 $err['trace'] = $e->getTraceAsString();
162 }
163 if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
164 $transaction->rollback();
165 }
166 return $err;
167 }
168 catch(Exception $e) {
169 if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
170 return 0;
171 }
172 $data = array();
173 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
174 if (CRM_Utils_Array::value('debug', $apiRequest['params'])) {
175 $err['trace'] = $e->getTraceAsString();
176 }
177 if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
178 $transaction->rollback();
179 }
180 return $err;
181 }
182 }
183
184 /**
185 * Look up the implementation for a given API request
186 *
187 * @param $apiRequest array with keys:
188 * - entity: string, required
189 * - action: string, required
190 * - params: array
191 * - version: scalar, required
192 *
193 * @return array with keys
194 * - function: callback (mixed)
195 * - is_generic: boolean
196 */
197 function _civicrm_api_resolve($apiRequest) {
198 static $cache;
199 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
200 if (isset($cache[$cachekey])) {
201 return $cache[$cachekey];
202 }
203
204 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
205 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
206
207 // Determine if there is an entity-specific implementation of the action
208 $stdFunction = civicrm_api_get_function_name($apiRequest['entity'], $apiRequest['action'], $apiRequest['version']);
209 if (function_exists($stdFunction)) {
210 // someone already loaded the appropriate file
211 // FIXME: This has the affect of masking bugs in load order; this is included to provide bug-compatibility
212 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
213 return $cache[$cachekey];
214 }
215
216 $stdFiles = array(
217 // By convention, the $camelName.php is more likely to contain the function, so test it first
218 'api/v' . $apiRequest['version'] . '/' . $camelName . '.php',
219 'api/v' . $apiRequest['version'] . '/' . $camelName . '/' . $actionCamelName . '.php',
220 );
221 foreach ($stdFiles as $stdFile) {
222 if (CRM_Utils_File::isIncludable($stdFile)) {
223 require_once $stdFile;
224 if (function_exists($stdFunction)) {
225 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
226 return $cache[$cachekey];
227 }
228 }
229 }
230
231 // Determine if there is a generic implementation of the action
232 require_once 'api/v3/Generic.php';
233 # $genericFunction = 'civicrm_api3_generic_' . $apiRequest['action'];
234 $genericFunction = civicrm_api_get_function_name('generic', $apiRequest['action'], $apiRequest['version']);
235 $genericFiles = array(
236 // By convention, the Generic.php is more likely to contain the function, so test it first
237 'api/v' . $apiRequest['version'] . '/Generic.php',
238 'api/v' . $apiRequest['version'] . '/Generic/' . $actionCamelName . '.php',
239 );
240 foreach ($genericFiles as $genericFile) {
241 if (CRM_Utils_File::isIncludable($genericFile)) {
242 require_once $genericFile;
243 if (function_exists($genericFunction)) {
244 $cache[$cachekey] = array('function' => $genericFunction, 'is_generic' => TRUE);
245 return $cache[$cachekey];
246 }
247 }
248 }
249
250 $cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
251 return $cache[$cachekey];
252 }
253 /**
254 * Version 3 wrapper for civicrm_api. Throws exception
255 * @param string $entity type of entities to deal with
256 * @param string $action create, get, delete or some special action name.
257 * @param array $params array to be passed to function
258 *
259 * @return array
260 *
261 */
262 function civicrm_api3($entity, $action, $params) {
263 $params['version'] = 3;
264 $result = civicrm_api($entity, $action, $params);
265 if(is_array($result) && !empty($result['is_error'])){
266 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
267 }
268 return $result;
269 }
270
271 /**
272 * Load/require all files related to an entity.
273 *
274 * This should not normally be called because it's does a file-system scan; it's
275 * only appropriate when introspection is really required (eg for "getActions").
276 *
277 * @param string $entity
278 * @return void
279 */
280 function _civicrm_api_loadEntity($entity, $version = 3) {
281 /*
282 $apiRequest = array();
283 $apiRequest['entity'] = $entity;
284 $apiRequest['action'] = 'pretty sure it will never exist. Trick to [try to] force resolve to scan everywhere';
285 $apiRequest['version'] = $version;
286 // look up function, file, is_generic
287 $apiRequest = _civicrm_api_resolve($apiRequest);
288 */
289
290 $camelName = _civicrm_api_get_camel_name($entity, $version);
291
292 // Check for master entity file; to match _civicrm_api_resolve(), only load the first one
293 $stdFile = 'api/v' . $version . '/' . $camelName . '.php';
294 if (CRM_Utils_File::isIncludable($stdFile)) {
295 require_once $stdFile;
296 }
297
298 // Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
299 $loaded_files = array(); // array($relativeFilePath => TRUE)
300 $include_dirs = array_unique(explode(PATH_SEPARATOR, get_include_path()));
301 foreach ($include_dirs as $include_dir) {
302 $action_dir = implode(DIRECTORY_SEPARATOR, array($include_dir, 'api', "v${version}", $camelName));
303 if (! is_dir($action_dir)) {
304 continue;
305 }
306
307 $iterator = new DirectoryIterator($action_dir);
308 foreach ($iterator as $fileinfo) {
309 $file = $fileinfo->getFilename();
310 if (array_key_exists($file, $loaded_files)) {
311 continue; // action provided by an earlier item on include_path
312 }
313
314 $parts = explode(".", $file);
315 if (end($parts) == "php" && !preg_match('/Tests?\.php$/', $file) ) {
316 require_once $action_dir . DIRECTORY_SEPARATOR . $file;
317 $loaded_files[$file] = TRUE;
318 }
319 }
320 }
321 }
322
323 /**
324 *
325 * @deprecated
326 */
327 function civicrm_api_get_function_name($entity, $action, $version = NULL) {
328
329 if (empty($version)) {
330 $version = civicrm_get_api_version();
331 }
332
333 $entity = _civicrm_api_get_entity_name_from_camel($entity);
334 return 'civicrm_api3' . '_' . $entity . '_' . $action;
335 }
336
337 /**
338 * We must be sure that every request uses only one version of the API.
339 *
340 * @param $desired_version : array or integer
341 * One chance to set the version number.
342 * After that, this version number will be used for the remaining request.
343 * This can either be a number, or an array(.., 'version' => $version, ..).
344 * This allows to directly pass the $params array.
345 */
346 function civicrm_get_api_version($desired_version = NULL) {
347
348 if (is_array($desired_version)) {
349 // someone gave the full $params array.
350 $params = $desired_version;
351 $desired_version = empty($params['version']) ? NULL : (int) $params['version'];
352 }
353 if (isset($desired_version) && is_integer($desired_version)) {
354 $_version = $desired_version;
355 }
356 else {
357 // we will set the default to version 3 as soon as we find that it works.
358 $_version = 3;
359 }
360 return $_version;
361 }
362
363 /**
364 * Check if the result is an error. Note that this function has been retained from
365 * api v2 for convenience but the result is more standardised in v3 and param
366 * 'format.is_success' => 1
367 * will result in a boolean success /fail being returned if that is what you need.
368 *
369 * @param array $params (reference ) input parameters
370 *
371 * @return boolean true if error, false otherwise
372 * @static void
373 * @access public
374 */
375 function civicrm_error($result) {
376 if (is_array($result)) {
377 return (array_key_exists('is_error', $result) &&
378 $result['is_error']
379 ) ? TRUE : FALSE;
380 }
381 return FALSE;
382 }
383
384 function _civicrm_api_get_camel_name($entity, $version = NULL) {
385 if (empty($version)) {
386 $version = civicrm_get_api_version();
387 }
388
389 $fragments = explode('_', $entity);
390 foreach ($fragments as & $fragment) {
391 $fragment = ucfirst($fragment);
392 }
393 // Special case: UFGroup, UFJoin, UFMatch, UFField
394 if ($fragments[0] === 'Uf') {
395 $fragments[0] = 'UF';
396 }
397 return implode('', $fragments);
398 }
399
400 /**
401 * Call any nested api calls
402 */
403 function _civicrm_api_call_nested_api(&$params, &$result, $action, $entity, $version) {
404 $entity = _civicrm_api_get_entity_name_from_camel($entity);
405 if(strtolower($action) == 'getsingle'){
406 // I don't understand the protocol here, but we don't want
407 // $result to be a recursive array
408 // $result['values'][0] = $result;
409 $oldResult = $result;
410 $result = array('values' => array(0 => $oldResult));
411 }
412 foreach ($params as $field => $newparams) {
413 if ((is_array($newparams) || $newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
414
415 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
416 if ($newparams === 1) {
417 $newparams = array('version' => $version);
418 }
419 // can be api_ or api.
420 $separator = $field[3];
421 if (!($separator == '.' || $separator == '_')) {
422 continue;
423 }
424 $subAPI = explode($separator, $field);
425
426 $subaction = empty($subAPI[2]) ? $action : $subAPI[2];
427 $subParams = array(
428 'debug' => CRM_Utils_Array::value('debug', $params),
429 );
430 $subEntity = $subAPI[1];
431
432 foreach ($result['values'] as $idIndex => $parentAPIValues) {
433
434 if (strtolower($subEntity) != 'contact') {
435 //contact spits the dummy at activity_id so what else won't it like?
436 //set entity_id & entity table based on the parent's id & entity. e.g for something like
437 //note if the parent call is contact 'entity_table' will be set to 'contact' & 'id' to the contact id from
438 //the parent call.
439 //in this case 'contact_id' will also be set to the parent's id
440 $subParams["entity_id"] = $parentAPIValues['id'];
441 $subParams['entity_table'] = 'civicrm_' . _civicrm_api_get_entity_name_from_camel($entity);
442 $subParams[strtolower($entity) . "_id"] = $parentAPIValues['id'];
443 }
444 if (strtolower($entity) != 'contact' && CRM_Utils_Array::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
445 //e.g. if event_id is in the values returned & subentity is event then pass in event_id as 'id'
446 //don't do this for contact as it does some wierd things like returning primary email &
447 //thus limiting the ability to chain email
448 //TODO - this might need the camel treatment
449 $subParams['id'] = $parentAPIValues[$subEntity . "_id"];
450 }
451
452 if (CRM_Utils_Array::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
453 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
454 }
455 // if we are dealing with the same entity pass 'id' through (useful for get + delete for example)
456 if (strtolower($entity) == strtolower($subEntity)) {
457 $subParams['id'] = $result['values'][$idIndex]['id'];
458 }
459
460
461 $subParams['version'] = $version;
462 if(!empty($params['check_permissions'])){
463 $subParams['check_permissions'] = $params['check_permissions'];
464 }
465 $subParams['sequential'] = 1;
466 $subParams['api.has_parent'] = 1;
467 if (array_key_exists(0, $newparams)) {
468 // it is a numerically indexed array - ie. multiple creates
469 foreach ($newparams as $entity => $entityparams) {
470 $subParams = array_merge($subParams, $entityparams);
471 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
472 $result['values'][$result['id']][$field][] = civicrm_api($subEntity, $subaction, $subParams);
473 if ($result['is_error'] === 1) {
474 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
475 }
476 }
477 }
478 else {
479
480 $subParams = array_merge($subParams, $newparams);
481 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
482 $result['values'][$idIndex][$field] = civicrm_api($subEntity, $subaction, $subParams);
483 if (!empty($result['is_error'])) {
484 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
485 }
486 }
487 }
488 }
489 }
490 if(strtolower($action) == 'getsingle'){
491 $result = $result['values'][0];
492 }
493 }
494
495 /**
496 * Swap out any $values vars - ie. the value after $value is swapped for the parent $result
497 * 'activity_type_id' => '$value.testfield',
498 'tag_id' => '$value.api.tag.create.id',
499 'tag1_id' => '$value.api.entity.create.0.id'
500 */
501 function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
502
503
504 foreach ($params as $field => $value) {
505
506 if (is_string($value) && substr($value, 0, 6) == '$value') {
507 $valuesubstitute = substr($value, 7);
508
509 if (!empty($parentResult[$valuesubstitute])) {
510 $params[$field] = $parentResult[$valuesubstitute];
511 }
512 else {
513
514 $stringParts = explode($separator, $value);
515 unset($stringParts[0]);
516
517 $fieldname = array_shift($stringParts);
518
519 //when our string is an array we will treat it as an array from that . onwards
520 $count = count($stringParts);
521 while ($count > 0) {
522 $fieldname .= "." . array_shift($stringParts);
523 if (array_key_exists($fieldname, $parentResult) && is_array($parentResult[$fieldname])) {
524 $arrayLocation = $parentResult[$fieldname];
525 foreach ($stringParts as $key => $value) {
526 $arrayLocation = CRM_Utils_Array::value($value, $arrayLocation);
527 }
528 $params[$field] = $arrayLocation;
529 }
530 $count = count($stringParts);
531 }
532 }
533 }
534 }
535 }
536
537 /**
538 * Convert possibly camel name to underscore separated entity name
539 *
540 * @param string $entity entity name in various formats e.g. Contribution, contribution, OptionValue, option_value, UFJoin, uf_join
541 * @return string $entity entity name in underscore separated format
542 *
543 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
544 */
545 function _civicrm_api_get_entity_name_from_camel($entity) {
546 if ($entity == strtolower($entity)) {
547 return $entity;
548 }
549 else {
550 $entity = ltrim(strtolower(str_replace('U_F',
551 'uf',
552 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
553 preg_replace('/(?=[A-Z])/', '_$0', $entity)
554 )), '_');
555 }
556 return $entity;
557 }
558
559 /**
560 * Having a DAO object find the entity name
561 * @param object $bao DAO being passed in
562 */
563 function _civicrm_api_get_entity_name_from_dao($bao){
564 $daoName = str_replace("BAO", "DAO", get_class($bao));
565 return _civicrm_api_get_entity_name_from_camel(CRM_Core_DAO_AllCoreTables::getBriefName($daoName));
566 }
567
568 /**
569 * Sets the tsLocale and dbLocale for multi-lingual sites.
570 * Some code duplication from CRM/Core/BAO/ConfigSetting.php retrieve()
571 * to avoid regressions from refactoring.
572 */
573 function _civicrm_api_set_locale($lcMessagesRequest) {
574 // We must validate whether the locale is valid, otherwise setting a bad
575 // dbLocale could probably lead to sql-injection.
576 $domain = new CRM_Core_DAO_Domain();
577 $domain->id = CRM_Core_Config::domainID();
578 $domain->find(TRUE);
579
580 if ($domain->config_backend) {
581 $defaults = unserialize($domain->config_backend);
582
583 // are we in a multi-language setup?
584 $multiLang = $domain->locales ? TRUE : FALSE;
585 $lcMessages = NULL;
586
587 // on multi-lang sites based on request and civicrm_uf_match
588 if ($multiLang) {
589 $languageLimit = array();
590 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
591 $languageLimit = $defaults['languageLimit'];
592 }
593
594 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
595 $lcMessages = $lcMessagesRequest;
596 }
597 else {
598 throw new API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
599 }
600 }
601
602 global $dbLocale;
603
604 // set suffix for table names - use views if more than one language
605 if ($lcMessages) {
606 $dbLocale = $multiLang && $lcMessages ? "_{$lcMessages}" : '';
607
608 // FIXME: an ugly hack to fix CRM-4041
609 global $tsLocale;
610 $tsLocale = $lcMessages;
611 }
612 }
613 }