Merge pull request #19390 from civicrm/php_version_bump
[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 switch ($apiRequest['version']) {
163 case 3:
164 if (!is_array($apiRequest['params'])) {
165 throw new \API_Exception('Input variable `params` is not an array', 2000);
166 }
167 require_once 'api/v3/utils.php';
168 _civicrm_api3_initialize();
169 break;
170
171 case 4:
172 // nothing to do
173 break;
174
175 default:
176 throw new \API_Exception('Unknown api version', 2000);
177 }
178 }
179
180 /**
181 * @param array $apiRequest
182 * @throws \API_Exception
183 */
184 protected function validate($apiRequest) {
185 }
186
187 /**
188 * Determine which, if any, service will execute the API request.
189 *
190 * @param array $apiRequest
191 * The full description of the API request.
192 * @throws Exception\NotImplementedException
193 * @return array
194 * A tuple with the provider-object and a revised apiRequest.
195 * Array(0 => ProviderInterface, 1 => array $apiRequest).
196 */
197 public function resolve($apiRequest) {
198 /** @var \Civi\API\Event\ResolveEvent $resolveEvent */
199 $resolveEvent = $this->dispatcher->dispatch('civi.api.resolve', new ResolveEvent($apiRequest, $this));
200 $apiRequest = $resolveEvent->getApiRequest();
201 if (!$resolveEvent->getApiProvider()) {
202 throw new \Civi\API\Exception\NotImplementedException("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
203 }
204 return [$resolveEvent->getApiProvider(), $apiRequest];
205 }
206
207 /**
208 * Determine if the API request is allowed (under current policy)
209 *
210 * @param \Civi\API\Provider\ProviderInterface $apiProvider
211 * The API provider responsible for executing the request.
212 * @param array $apiRequest
213 * The full description of the API request.
214 * @throws Exception\UnauthorizedException
215 */
216 public function authorize($apiProvider, $apiRequest) {
217 /** @var \Civi\API\Event\AuthorizeEvent $event */
218 $event = $this->dispatcher->dispatch('civi.api.authorize', new AuthorizeEvent($apiProvider, $apiRequest, $this));
219 if (!$event->isAuthorized()) {
220 throw new \Civi\API\Exception\UnauthorizedException("Authorization failed");
221 }
222 }
223
224 /**
225 * Allow third-party code to manipulate the API request before execution.
226 *
227 * @param \Civi\API\Provider\ProviderInterface $apiProvider
228 * The API provider responsible for executing the request.
229 * @param array $apiRequest
230 * The full description of the API request.
231 * @return array
232 * [0 => ProviderInterface $provider, 1 => array $apiRequest]
233 * The revised API request.
234 */
235 public function prepare($apiProvider, $apiRequest) {
236 /** @var \Civi\API\Event\PrepareEvent $event */
237 $event = $this->dispatcher->dispatch('civi.api.prepare', new PrepareEvent($apiProvider, $apiRequest, $this));
238 return [$event->getApiProvider(), $event->getApiRequest()];
239 }
240
241 /**
242 * Allow third-party code to manipulate the API response after execution.
243 *
244 * @param \Civi\API\Provider\ProviderInterface $apiProvider
245 * The API provider responsible for executing the request.
246 * @param array $apiRequest
247 * The full description of the API request.
248 * @param array $result
249 * The response to return to the client.
250 * @return mixed
251 * The revised $result.
252 */
253 public function respond($apiProvider, $apiRequest, $result) {
254 /** @var \Civi\API\Event\RespondEvent $event */
255 $event = $this->dispatcher->dispatch('civi.api.respond', new RespondEvent($apiProvider, $apiRequest, $result, $this));
256 return $event->getResponse();
257 }
258
259 /**
260 * @param int $version
261 * API version.
262 * @return array
263 * Array<string>.
264 */
265 public function getEntityNames($version) {
266 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
267 $entityNames = [];
268 foreach ($this->getApiProviders() as $provider) {
269 /** @var \Civi\API\Provider\ProviderInterface $provider */
270 $entityNames = array_merge($entityNames, $provider->getEntityNames($version));
271 }
272 $entityNames = array_unique($entityNames);
273 sort($entityNames);
274 return $entityNames;
275 }
276
277 /**
278 * @param int $version
279 * API version.
280 * @param string $entity
281 * API entity.
282 * @return array
283 * Array<string>
284 */
285 public function getActionNames($version, $entity) {
286 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
287 $actionNames = [];
288 foreach ($this->getApiProviders() as $provider) {
289 /** @var \Civi\API\Provider\ProviderInterface $provider */
290 $actionNames = array_merge($actionNames, $provider->getActionNames($version, $entity));
291 }
292 $actionNames = array_unique($actionNames);
293 sort($actionNames);
294 return $actionNames;
295 }
296
297 /**
298 * @param \Exception $e
299 * An unhandled exception.
300 * @param array $apiRequest
301 * The full description of the API request.
302 *
303 * @return array
304 * API response.
305 * @throws \API_Exception
306 */
307 public function formatException($e, $apiRequest) {
308 $data = [];
309 if (!empty($apiRequest['params']['debug'])) {
310 $data['trace'] = $e->getTraceAsString();
311 }
312 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
313 }
314
315 /**
316 * @param \API_Exception $e
317 * An unhandled exception.
318 * @param array $apiRequest
319 * The full description of the API request.
320 *
321 * @return array
322 * (API response)
323 * @throws \API_Exception
324 */
325 public function formatApiException($e, $apiRequest) {
326 $data = $e->getExtraParams();
327 $data['entity'] = $apiRequest['entity'] ?? NULL;
328 $data['action'] = $apiRequest['action'] ?? NULL;
329
330 if (\CRM_Utils_Array::value('debug', \CRM_Utils_Array::value('params', $apiRequest))
331 // prevent recursion
332 && empty($data['trace'])
333 ) {
334 $data['trace'] = $e->getTraceAsString();
335 }
336
337 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
338 }
339
340 /**
341 * @param \PEAR_Exception $e
342 * An unhandled exception.
343 * @param array $apiRequest
344 * The full description of the API request.
345 *
346 * @return array
347 * API response.
348 *
349 * @throws \API_Exception
350 */
351 public function formatPearException($e, $apiRequest) {
352 $data = [];
353 $error = $e->getCause();
354 if ($error instanceof \DB_Error) {
355 $data['error_code'] = \DB::errorMessage($error->getCode());
356 $data['sql'] = $error->getDebugInfo();
357 }
358 if (!empty($apiRequest['params']['debug'])) {
359 if (method_exists($e, 'getUserInfo')) {
360 $data['debug_info'] = $error->getUserInfo();
361 }
362 if (method_exists($e, 'getExtraData')) {
363 $data['debug_info'] = $data + $error->getExtraData();
364 }
365 $data['trace'] = $e->getTraceAsString();
366 }
367 else {
368 $data['tip'] = 'add debug=1 to your API call to have more info about the error';
369 }
370
371 return $this->createError($e->getMessage(), $data, $apiRequest);
372 }
373
374 /**
375 * @param string $msg
376 * Descriptive error message.
377 * @param array $data
378 * Error data.
379 * @param array $apiRequest
380 * The full description of the API request.
381 * @param mixed $code
382 * Doesn't appear to be used.
383 *
384 * @throws \API_Exception
385 * @return array
386 * Array<type>.
387 */
388 public function createError($msg, $data, $apiRequest, $code = NULL) {
389 // FIXME what to do with $code?
390 if ($msg === 'DB Error: constraint violation' || substr($msg, 0, 9) == 'DB Error:' || $msg == 'DB Error: already exists') {
391 try {
392 $fields = _civicrm_api3_api_getfields($apiRequest);
393 _civicrm_api3_validate_foreign_keys($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
394 }
395 catch (\Exception $e) {
396 $msg = $e->getMessage();
397 }
398 }
399
400 $data = \civicrm_api3_create_error($msg, $data);
401
402 if (isset($apiRequest['params']) && is_array($apiRequest['params']) && !empty($apiRequest['params']['api.has_parent'])) {
403 $errorCode = empty($data['error_code']) ? 'chained_api_failed' : $data['error_code'];
404 throw new \API_Exception('Error in call to ' . $apiRequest['entity'] . '_' . $apiRequest['action'] . ' : ' . $msg, $errorCode, $data);
405 }
406
407 return $data;
408 }
409
410 /**
411 * @param array $apiRequest
412 * The full description of the API request.
413 * @param array $result
414 * The response to return to the client.
415 * @return mixed
416 */
417 public function formatResult($apiRequest, $result) {
418 if (isset($apiRequest, $apiRequest['params'])) {
419 if (isset($apiRequest['params']['format.is_success']) && $apiRequest['params']['format.is_success'] == 1) {
420 return (empty($result['is_error'])) ? 1 : 0;
421 }
422
423 if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) {
424 // FIXME dispatch
425 return $result['id'];
426 }
427 }
428 return $result;
429 }
430
431 /**
432 * @return array<ProviderInterface>
433 */
434 public function getApiProviders() {
435 return $this->apiProviders;
436 }
437
438 /**
439 * @param array $apiProviders
440 * Array<ProviderInterface>.
441 * @return Kernel
442 */
443 public function setApiProviders($apiProviders) {
444 $this->apiProviders = $apiProviders;
445 return $this;
446 }
447
448 /**
449 * @param \Civi\API\Provider\ProviderInterface $apiProvider
450 * The API provider responsible for executing the request.
451 * @return Kernel
452 */
453 public function registerApiProvider($apiProvider) {
454 $this->apiProviders[] = $apiProvider;
455 if ($apiProvider instanceof \Symfony\Component\EventDispatcher\EventSubscriberInterface) {
456 $this->getDispatcher()->addSubscriber($apiProvider);
457 }
458 return $this;
459 }
460
461 /**
462 * @return \Symfony\Component\EventDispatcher\EventDispatcher
463 */
464 public function getDispatcher() {
465 return $this->dispatcher;
466 }
467
468 /**
469 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
470 * The event dispatcher which receives kernel events.
471 * @return Kernel
472 */
473 public function setDispatcher($dispatcher) {
474 $this->dispatcher = $dispatcher;
475 return $this;
476 }
477
478 }