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