Merge pull request #20321 from mattwire/loggedincontactid
[civicrm-core.git] / Civi / API / Kernel.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11 namespace Civi\API;
12
13 use Civi\API\Event\AuthorizeEvent;
14 use Civi\API\Event\PrepareEvent;
15 use Civi\API\Event\ExceptionEvent;
16 use Civi\API\Event\ResolveEvent;
17 use Civi\API\Event\RespondEvent;
18
19 /**
20 * @package Civi
21 * @copyright CiviCRM LLC https://civicrm.org/licensing
22 */
23 class Kernel {
24
25 /**
26 * @var \Symfony\Component\EventDispatcher\EventDispatcher
27 */
28 protected $dispatcher;
29
30 /**
31 * @var \Civi\API\Provider\ProviderInterface[]
32 */
33 protected $apiProviders;
34
35 /**
36 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
37 * The event dispatcher which receives kernel events.
38 * @param array $apiProviders
39 * Array of ProviderInterface.
40 */
41 public function __construct($dispatcher, $apiProviders = []) {
42 $this->apiProviders = $apiProviders;
43 $this->dispatcher = $dispatcher;
44 }
45
46 /**
47 * @param string $entity
48 * Name of entity: e.g. Contact, Activity, Event
49 * @param string $action
50 * Name of action: e.g. create, get, delete
51 * @param array $params
52 * Array to be passed to API function.
53 *
54 * @return array|int
55 * @throws \API_Exception
56 * @see runSafe
57 * @deprecated
58 */
59 public function run($entity, $action, $params) {
60 return $this->runSafe($entity, $action, $params);
61 }
62
63 /**
64 * Parse and execute an API request. Any errors will be converted to
65 * normal format.
66 *
67 * @param string $entity
68 * Name of entity: e.g. Contact, Activity, Event
69 * @param string $action
70 * Name of action: e.g. create, get, delete
71 * @param array $params
72 * Array to be passed to API function.
73 *
74 * @return array|int
75 * @throws \API_Exception
76 */
77 public function runSafe($entity, $action, $params) {
78 $apiRequest = [];
79 try {
80 $apiRequest = Request::create($entity, $action, $params);
81 $apiResponse = $this->runRequest($apiRequest);
82 return $this->formatResult($apiRequest, $apiResponse);
83 }
84 catch (\Exception $e) {
85 if ($apiRequest) {
86 $this->dispatcher->dispatch('civi.api.exception', new ExceptionEvent($e, NULL, $apiRequest, $this));
87 }
88
89 if ($e instanceof \PEAR_Exception) {
90 $err = $this->formatPearException($e, $apiRequest);
91 }
92 elseif ($e instanceof \API_Exception) {
93 $err = $this->formatApiException($e, $apiRequest);
94 }
95 else {
96 $err = $this->formatException($e, $apiRequest);
97 }
98
99 return $this->formatResult($apiRequest, $err);
100 }
101 }
102
103 /**
104 * Determine if a hypothetical API call would be authorized.
105 *
106 * @param string $entity
107 * Type of entities to deal with.
108 * @param string $action
109 * Create, get, delete or some special action name.
110 * @param array $params
111 * Array to be passed to function.
112 *
113 * @return bool
114 * TRUE if authorization would succeed.
115 * @throws \Exception
116 */
117 public function runAuthorize($entity, $action, $params) {
118 $apiProvider = NULL;
119 $apiRequest = Request::create($entity, $action, $params);
120
121 try {
122 $this->boot($apiRequest);
123 list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
124 $this->authorize($apiProvider, $apiRequest);
125 return TRUE;
126 }
127 catch (\Civi\API\Exception\UnauthorizedException $e) {
128 return FALSE;
129 }
130 }
131
132 /**
133 * Execute an API v3 or v4 request.
134 *
135 * The request must be in canonical format. Exceptions will be propagated out.
136 *
137 * @param array|\Civi\Api4\Generic\AbstractAction $apiRequest
138 * @return array|\Civi\Api4\Generic\Result
139 * @throws \API_Exception
140 * @throws \Civi\API\Exception\NotImplementedException
141 * @throws \Civi\API\Exception\UnauthorizedException
142 */
143 public function runRequest($apiRequest) {
144 $this->boot($apiRequest);
145
146 list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
147 $this->authorize($apiProvider, $apiRequest);
148 list ($apiProvider, $apiRequest) = $this->prepare($apiProvider, $apiRequest);
149 $result = $apiProvider->invoke($apiRequest);
150
151 return $this->respond($apiProvider, $apiRequest, $result);
152 }
153
154 /**
155 * Bootstrap - Load basic dependencies and sanity-check inputs.
156 *
157 * @param \Civi\Api4\Generic\AbstractAction|array $apiRequest
158 * @throws \API_Exception
159 */
160 public function boot($apiRequest) {
161 require_once 'api/Exception.php';
162 // the create error function loads some functions from utils
163 // so this require is also needed for apiv4 until such time as
164 // we alter create error.
165 require_once 'api/v3/utils.php';
166 switch ($apiRequest['version']) {
167 case 3:
168 if (!is_array($apiRequest['params'])) {
169 throw new \API_Exception('Input variable `params` is not an array', 2000);
170 }
171 _civicrm_api3_initialize();
172 break;
173
174 case 4:
175 // nothing to do
176 break;
177
178 default:
179 throw new \API_Exception('Unknown api version', 2000);
180 }
181 }
182
183 /**
184 * @param array $apiRequest
185 * @throws \API_Exception
186 */
187 protected function validate($apiRequest) {
188 }
189
190 /**
191 * Determine which, if any, service will execute the API request.
192 *
193 * @param array $apiRequest
194 * The full description of the API request.
195 * @throws Exception\NotImplementedException
196 * @return array
197 * A tuple with the provider-object and a revised apiRequest.
198 * Array(0 => ProviderInterface, 1 => array $apiRequest).
199 */
200 public function resolve($apiRequest) {
201 /** @var \Civi\API\Event\ResolveEvent $resolveEvent */
202 $resolveEvent = $this->dispatcher->dispatch('civi.api.resolve', new ResolveEvent($apiRequest, $this));
203 $apiRequest = $resolveEvent->getApiRequest();
204 if (!$resolveEvent->getApiProvider()) {
205 throw new \Civi\API\Exception\NotImplementedException("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
206 }
207 return [$resolveEvent->getApiProvider(), $apiRequest];
208 }
209
210 /**
211 * Determine if the API request is allowed (under current policy)
212 *
213 * @param \Civi\API\Provider\ProviderInterface $apiProvider
214 * The API provider responsible for executing the request.
215 * @param array $apiRequest
216 * The full description of the API request.
217 * @throws Exception\UnauthorizedException
218 */
219 public function authorize($apiProvider, $apiRequest) {
220 /** @var \Civi\API\Event\AuthorizeEvent $event */
221 $event = $this->dispatcher->dispatch('civi.api.authorize', new AuthorizeEvent($apiProvider, $apiRequest, $this, \CRM_Core_Session::getLoggedInContactID() ?: 0));
222 if (!$event->isAuthorized()) {
223 throw new \Civi\API\Exception\UnauthorizedException("Authorization failed");
224 }
225 }
226
227 /**
228 * Allow third-party code to manipulate the API request before execution.
229 *
230 * @param \Civi\API\Provider\ProviderInterface $apiProvider
231 * The API provider responsible for executing the request.
232 * @param array $apiRequest
233 * The full description of the API request.
234 * @return array
235 * [0 => ProviderInterface $provider, 1 => array $apiRequest]
236 * The revised API request.
237 */
238 public function prepare($apiProvider, $apiRequest) {
239 /** @var \Civi\API\Event\PrepareEvent $event */
240 $event = $this->dispatcher->dispatch('civi.api.prepare', new PrepareEvent($apiProvider, $apiRequest, $this));
241 return [$event->getApiProvider(), $event->getApiRequest()];
242 }
243
244 /**
245 * Allow third-party code to manipulate the API response after execution.
246 *
247 * @param \Civi\API\Provider\ProviderInterface $apiProvider
248 * The API provider responsible for executing the request.
249 * @param array $apiRequest
250 * The full description of the API request.
251 * @param array $result
252 * The response to return to the client.
253 * @return mixed
254 * The revised $result.
255 */
256 public function respond($apiProvider, $apiRequest, $result) {
257 /** @var \Civi\API\Event\RespondEvent $event */
258 $event = $this->dispatcher->dispatch('civi.api.respond', new RespondEvent($apiProvider, $apiRequest, $result, $this));
259 return $event->getResponse();
260 }
261
262 /**
263 * @param int $version
264 * API version.
265 * @return array
266 * Array<string>.
267 */
268 public function getEntityNames($version) {
269 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
270 $entityNames = [];
271 foreach ($this->getApiProviders() as $provider) {
272 /** @var \Civi\API\Provider\ProviderInterface $provider */
273 $entityNames = array_merge($entityNames, $provider->getEntityNames($version));
274 }
275 $entityNames = array_unique($entityNames);
276 sort($entityNames);
277 return $entityNames;
278 }
279
280 /**
281 * @param int $version
282 * API version.
283 * @param string $entity
284 * API entity.
285 * @return array
286 * Array<string>
287 */
288 public function getActionNames($version, $entity) {
289 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
290 $actionNames = [];
291 foreach ($this->getApiProviders() as $provider) {
292 /** @var \Civi\API\Provider\ProviderInterface $provider */
293 $actionNames = array_merge($actionNames, $provider->getActionNames($version, $entity));
294 }
295 $actionNames = array_unique($actionNames);
296 sort($actionNames);
297 return $actionNames;
298 }
299
300 /**
301 * @param \Exception $e
302 * An unhandled exception.
303 * @param array $apiRequest
304 * The full description of the API request.
305 *
306 * @return array
307 * API response.
308 * @throws \API_Exception
309 */
310 public function formatException($e, $apiRequest) {
311 $data = [];
312 if (!empty($apiRequest['params']['debug'])) {
313 $data['trace'] = $e->getTraceAsString();
314 }
315 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
316 }
317
318 /**
319 * @param \API_Exception $e
320 * An unhandled exception.
321 * @param array $apiRequest
322 * The full description of the API request.
323 *
324 * @return array
325 * (API response)
326 * @throws \API_Exception
327 */
328 public function formatApiException($e, $apiRequest) {
329 $data = $e->getExtraParams();
330 $data['entity'] = $apiRequest['entity'] ?? NULL;
331 $data['action'] = $apiRequest['action'] ?? NULL;
332
333 if (\CRM_Utils_Array::value('debug', \CRM_Utils_Array::value('params', $apiRequest))
334 // prevent recursion
335 && empty($data['trace'])
336 ) {
337 $data['trace'] = $e->getTraceAsString();
338 }
339
340 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
341 }
342
343 /**
344 * @param \PEAR_Exception $e
345 * An unhandled exception.
346 * @param array $apiRequest
347 * The full description of the API request.
348 *
349 * @return array
350 * API response.
351 *
352 * @throws \API_Exception
353 */
354 public function formatPearException($e, $apiRequest) {
355 $data = [];
356 $error = $e->getCause();
357 if ($error instanceof \DB_Error) {
358 $data['error_code'] = \DB::errorMessage($error->getCode());
359 $data['sql'] = $error->getDebugInfo();
360 }
361 if (!empty($apiRequest['params']['debug'])) {
362 if (method_exists($e, 'getUserInfo')) {
363 $data['debug_info'] = $error->getUserInfo();
364 }
365 if (method_exists($e, 'getExtraData')) {
366 $data['debug_info'] = $data + $error->getExtraData();
367 }
368 $data['trace'] = $e->getTraceAsString();
369 }
370 else {
371 $data['tip'] = 'add debug=1 to your API call to have more info about the error';
372 }
373
374 return $this->createError($e->getMessage(), $data, $apiRequest);
375 }
376
377 /**
378 * @param string $msg
379 * Descriptive error message.
380 * @param array $data
381 * Error data.
382 * @param array $apiRequest
383 * The full description of the API request.
384 * @param mixed $code
385 * Doesn't appear to be used.
386 *
387 * @throws \API_Exception
388 * @return array
389 * Array<type>.
390 */
391 public function createError($msg, $data, $apiRequest, $code = NULL) {
392 // FIXME what to do with $code?
393 if ($msg === 'DB Error: constraint violation' || substr($msg, 0, 9) == 'DB Error:' || $msg == 'DB Error: already exists') {
394 try {
395 $fields = _civicrm_api3_api_getfields($apiRequest);
396 _civicrm_api3_validate_foreign_keys($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
397 }
398 catch (\Exception $e) {
399 $msg = $e->getMessage();
400 }
401 }
402
403 $data = \civicrm_api3_create_error($msg, $data);
404
405 if (isset($apiRequest['params']) && is_array($apiRequest['params']) && !empty($apiRequest['params']['api.has_parent'])) {
406 $errorCode = empty($data['error_code']) ? 'chained_api_failed' : $data['error_code'];
407 throw new \API_Exception('Error in call to ' . $apiRequest['entity'] . '_' . $apiRequest['action'] . ' : ' . $msg, $errorCode, $data);
408 }
409
410 return $data;
411 }
412
413 /**
414 * @param array $apiRequest
415 * The full description of the API request.
416 * @param array $result
417 * The response to return to the client.
418 * @return mixed
419 */
420 public function formatResult($apiRequest, $result) {
421 if (isset($apiRequest, $apiRequest['params'])) {
422 if (isset($apiRequest['params']['format.is_success']) && $apiRequest['params']['format.is_success'] == 1) {
423 return (empty($result['is_error'])) ? 1 : 0;
424 }
425
426 if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) {
427 // FIXME dispatch
428 return $result['id'];
429 }
430 }
431 return $result;
432 }
433
434 /**
435 * @return array<ProviderInterface>
436 */
437 public function getApiProviders() {
438 return $this->apiProviders;
439 }
440
441 /**
442 * @param array $apiProviders
443 * Array<ProviderInterface>.
444 * @return Kernel
445 */
446 public function setApiProviders($apiProviders) {
447 $this->apiProviders = $apiProviders;
448 return $this;
449 }
450
451 /**
452 * @param \Civi\API\Provider\ProviderInterface $apiProvider
453 * The API provider responsible for executing the request.
454 * @return Kernel
455 */
456 public function registerApiProvider($apiProvider) {
457 $this->apiProviders[] = $apiProvider;
458 if ($apiProvider instanceof \Symfony\Component\EventDispatcher\EventSubscriberInterface) {
459 $this->getDispatcher()->addSubscriber($apiProvider);
460 }
461 return $this;
462 }
463
464 /**
465 * @return \Symfony\Component\EventDispatcher\EventDispatcher
466 */
467 public function getDispatcher() {
468 return $this->dispatcher;
469 }
470
471 /**
472 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
473 * The event dispatcher which receives kernel events.
474 * @return Kernel
475 */
476 public function setDispatcher($dispatcher) {
477 $this->dispatcher = $dispatcher;
478 return $this;
479 }
480
481 }