390dda1f63287843dd9a35de1c42afab7d3f757e
[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-2014
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 * @param null $extra
21 *
22 * @return array|int
23 */
24 function civicrm_api($entity, $action, $params, $extra = NULL) {
25 return \Civi\Core\Container::singleton()->get('civi_api_kernel')->run($entity, $action, $params, $extra);
26 }
27
28 /**
29 * Version 3 wrapper for civicrm_api. Throws exception
30 *
31 * @param string $entity type of entities to deal with
32 * @param string $action create, get, delete or some special action name.
33 * @param array $params array to be passed to function
34 *
35 * @throws CiviCRM_API3_Exception
36 * @return array
37 */
38 function civicrm_api3($entity, $action, $params = array()) {
39 $params['version'] = 3;
40 $result = civicrm_api($entity, $action, $params);
41 if(is_array($result) && !empty($result['is_error'])){
42 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
43 }
44 return $result;
45 }
46
47 /**
48 * Function to call getfields from api wrapper. This function ensures that settings that could alter
49 * getfields output (e.g. action for all api & profile_id for profile api ) are consistently passed in.
50 *
51 * We check whether the api call is 'getfields' because if getfields is being called we return an empty array
52 * as no alias swapping, validation or default filling is done on getfields & we want to avoid a loop
53 *
54 * @todo other output modifiers include contact_type
55 *
56 * @param array $apiRequest
57 * @return array getfields output
58 */
59 function _civicrm_api3_api_getfields(&$apiRequest) {
60 if (strtolower($apiRequest['action'] == 'getfields')) {
61 // the main param getfields takes is 'action' - however this param is not compatible with REST
62 // so we accept 'api_action' as an alias of action on getfields
63 if (!empty($apiRequest['params']['api_action'])) {
64 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
65 // unset($apiRequest['params']['api_action']);
66 }
67 return array('action' => array('api.aliases' => array('api_action')));
68 }
69 $getFieldsParams = array('action' => $apiRequest['action']);
70 $entity = $apiRequest['entity'];
71 if($entity == 'profile' && array_key_exists('profile_id', $apiRequest['params'])) {
72 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
73 }
74 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
75 return $fields['values'];
76 }
77
78 /**
79 * Check if the result is an error. Note that this function has been retained from
80 * api v2 for convenience but the result is more standardised in v3 and param
81 * 'format.is_success' => 1
82 * will result in a boolean success /fail being returned if that is what you need.
83 *
84 * @param $result
85 *
86 * @internal param array $params (reference ) input parameters
87 *
88 * @return boolean true if error, false otherwise
89 * @static void
90 * @access public
91 */
92 function civicrm_error($result) {
93 if (is_array($result)) {
94 return (array_key_exists('is_error', $result) &&
95 $result['is_error']
96 ) ? TRUE : FALSE;
97 }
98 return FALSE;
99 }
100
101 function _civicrm_api_get_camel_name($entity, $version = NULL) {
102 $fragments = explode('_', $entity);
103 foreach ($fragments as & $fragment) {
104 $fragment = ucfirst($fragment);
105 }
106 // Special case: UFGroup, UFJoin, UFMatch, UFField
107 if ($fragments[0] === 'Uf') {
108 $fragments[0] = 'UF';
109 }
110 return implode('', $fragments);
111 }
112
113 /**
114 * Call any nested api calls
115 */
116 function _civicrm_api_call_nested_api(&$params, &$result, $action, $entity, $version) {
117 $entity = _civicrm_api_get_entity_name_from_camel($entity);
118
119 //we don't need to worry about nested api in the getfields/getoptions actions, so just return immediately
120 if (in_array(strtolower($action), array('getfields', 'getoptions'))) {
121 return;
122 }
123
124 if(strtolower($action) == 'getsingle'){
125 // I don't understand the protocol here, but we don't want
126 // $result to be a recursive array
127 // $result['values'][0] = $result;
128 $oldResult = $result;
129 $result = array('values' => array(0 => $oldResult));
130 }
131 foreach ($params as $field => $newparams) {
132 if ((is_array($newparams) || $newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
133
134 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
135 if ($newparams === 1) {
136 $newparams = array('version' => $version);
137 }
138 // can be api_ or api.
139 $separator = $field[3];
140 if (!($separator == '.' || $separator == '_')) {
141 continue;
142 }
143 $subAPI = explode($separator, $field);
144
145 $subaction = empty($subAPI[2]) ? $action : $subAPI[2];
146 $subParams = array(
147 'debug' => CRM_Utils_Array::value('debug', $params),
148 );
149 $subEntity = $subAPI[1];
150
151 foreach ($result['values'] as $idIndex => $parentAPIValues) {
152
153 if (strtolower($subEntity) != 'contact') {
154 //contact spits the dummy at activity_id so what else won't it like?
155 //set entity_id & entity table based on the parent's id & entity. e.g for something like
156 //note if the parent call is contact 'entity_table' will be set to 'contact' & 'id' to the contact id from
157 //the parent call.
158 //in this case 'contact_id' will also be set to the parent's id
159 $subParams["entity_id"] = $parentAPIValues['id'];
160 $subParams['entity_table'] = 'civicrm_' . _civicrm_api_get_entity_name_from_camel($entity);
161 $subParams[strtolower($entity) . "_id"] = $parentAPIValues['id'];
162 }
163 if (strtolower($entity) != 'contact' && CRM_Utils_Array::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
164 //e.g. if event_id is in the values returned & subentity is event then pass in event_id as 'id'
165 //don't do this for contact as it does some wierd things like returning primary email &
166 //thus limiting the ability to chain email
167 //TODO - this might need the camel treatment
168 $subParams['id'] = $parentAPIValues[$subEntity . "_id"];
169 }
170
171 if (CRM_Utils_Array::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
172 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
173 }
174 // if we are dealing with the same entity pass 'id' through (useful for get + delete for example)
175 if (strtolower($entity) == strtolower($subEntity)) {
176 $subParams['id'] = $result['values'][$idIndex]['id'];
177 }
178
179
180 $subParams['version'] = $version;
181 if(!empty($params['check_permissions'])){
182 $subParams['check_permissions'] = $params['check_permissions'];
183 }
184 $subParams['sequential'] = 1;
185 $subParams['api.has_parent'] = 1;
186 if (array_key_exists(0, $newparams)) {
187 $genericParams = $subParams;
188 // it is a numerically indexed array - ie. multiple creates
189 foreach ($newparams as $entityparams) {
190 $subParams = array_merge($genericParams, $entityparams);
191 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
192 $result['values'][$result['id']][$field][] = civicrm_api($subEntity, $subaction, $subParams);
193 if ($result['is_error'] === 1) {
194 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
195 }
196 }
197 }
198 else {
199
200 $subParams = array_merge($subParams, $newparams);
201 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
202 $result['values'][$idIndex][$field] = civicrm_api($subEntity, $subaction, $subParams);
203 if (!empty($result['is_error'])) {
204 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
205 }
206 }
207 }
208 }
209 }
210 if(strtolower($action) == 'getsingle'){
211 $result = $result['values'][0];
212 }
213 }
214
215 /**
216 * Swap out any $values vars - ie. the value after $value is swapped for the parent $result
217 * 'activity_type_id' => '$value.testfield',
218 'tag_id' => '$value.api.tag.create.id',
219 'tag1_id' => '$value.api.entity.create.0.id'
220 */
221 function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
222
223
224 foreach ($params as $field => $value) {
225
226 if (is_string($value) && substr($value, 0, 6) == '$value') {
227 $valuesubstitute = substr($value, 7);
228
229 if (!empty($parentResult[$valuesubstitute])) {
230 $params[$field] = $parentResult[$valuesubstitute];
231 }
232 else {
233
234 $stringParts = explode($separator, $value);
235 unset($stringParts[0]);
236
237 $fieldname = array_shift($stringParts);
238
239 //when our string is an array we will treat it as an array from that . onwards
240 $count = count($stringParts);
241 while ($count > 0) {
242 $fieldname .= "." . array_shift($stringParts);
243 if (array_key_exists($fieldname, $parentResult) && is_array($parentResult[$fieldname])) {
244 $arrayLocation = $parentResult[$fieldname];
245 foreach ($stringParts as $key => $value) {
246 $arrayLocation = CRM_Utils_Array::value($value, $arrayLocation);
247 }
248 $params[$field] = $arrayLocation;
249 }
250 $count = count($stringParts);
251 }
252 }
253 }
254 }
255 }
256
257 /**
258 * Convert possibly camel name to underscore separated entity name
259 *
260 * @param string $entity entity name in various formats e.g. Contribution, contribution, OptionValue, option_value, UFJoin, uf_join
261 * @return string $entity entity name in underscore separated format
262 *
263 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
264 */
265 function _civicrm_api_get_entity_name_from_camel($entity) {
266 if ($entity == strtolower($entity)) {
267 return $entity;
268 }
269 else {
270 $entity = ltrim(strtolower(str_replace('U_F',
271 'uf',
272 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
273 preg_replace('/(?=[A-Z])/', '_$0', $entity)
274 )), '_');
275 }
276 return $entity;
277 }
278
279 /**
280 * Having a DAO object find the entity name
281 * @param object $bao DAO being passed in
282 * @return string
283 */
284 function _civicrm_api_get_entity_name_from_dao($bao){
285 $daoName = str_replace("BAO", "DAO", get_class($bao));
286 return _civicrm_api_get_entity_name_from_camel(CRM_Core_DAO_AllCoreTables::getBriefName($daoName));
287 }
288