3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
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
;
21 * @copyright CiviCRM LLC https://civicrm.org/licensing
26 * @var \Symfony\Component\EventDispatcher\EventDispatcher
28 protected $dispatcher;
31 * @var \Civi\API\Provider\ProviderInterface[]
33 protected $apiProviders;
36 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
37 * The event dispatcher which receives kernel events.
38 * @param array $apiProviders
39 * Array of ProviderInterface.
41 public function __construct($dispatcher, $apiProviders = []) {
42 $this->apiProviders
= $apiProviders;
43 $this->dispatcher
= $dispatcher;
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.
55 * @throws \API_Exception
59 public function run($entity, $action, $params) {
60 return $this->runSafe($entity, $action, $params);
64 * Parse and execute an API request. Any errors will be converted to
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.
75 * @throws \API_Exception
77 public function runSafe($entity, $action, $params) {
80 $apiRequest = Request
::create($entity, $action, $params);
81 $apiResponse = $this->runRequest($apiRequest);
82 return $this->formatResult($apiRequest, $apiResponse);
84 catch (\Exception
$e) {
86 $this->dispatcher
->dispatch('civi.api.exception', new ExceptionEvent($e, NULL, $apiRequest, $this));
89 if ($e instanceof \PEAR_Exception
) {
90 $err = $this->formatPearException($e, $apiRequest);
92 elseif ($e instanceof \API_Exception
) {
93 $err = $this->formatApiException($e, $apiRequest);
96 $err = $this->formatException($e, $apiRequest);
99 return $this->formatResult($apiRequest, $err);
104 * Determine if a hypothetical API call would be authorized.
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.
114 * TRUE if authorization would succeed.
117 public function runAuthorize($entity, $action, $params) {
119 $apiRequest = Request
::create($entity, $action, $params);
122 $this->boot($apiRequest);
123 list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
124 $this->authorize($apiProvider, $apiRequest);
127 catch (\Civi\API\Exception\UnauthorizedException
$e) {
133 * Execute an API v3 or v4 request.
135 * The request must be in canonical format. Exceptions will be propagated out.
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
143 public function runRequest($apiRequest) {
144 $this->boot($apiRequest);
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);
151 return $this->respond($apiProvider, $apiRequest, $result);
155 * Bootstrap - Load basic dependencies and sanity-check inputs.
157 * @param \Civi\Api4\Generic\AbstractAction|array $apiRequest
158 * @throws \API_Exception
160 public function boot($apiRequest) {
161 require_once 'api/Exception.php';
162 switch ($apiRequest['version']) {
164 if (!is_array($apiRequest['params'])) {
165 throw new \
API_Exception('Input variable `params` is not an array', 2000);
167 require_once 'api/v3/utils.php';
168 _civicrm_api3_initialize();
176 throw new \
API_Exception('Unknown api version', 2000);
181 * @param array $apiRequest
182 * @throws \API_Exception
184 protected function validate($apiRequest) {
188 * Determine which, if any, service will execute the API request.
190 * @param array $apiRequest
191 * The full description of the API request.
192 * @throws Exception\NotImplementedException
194 * A tuple with the provider-object and a revised apiRequest.
195 * Array(0 => ProviderInterface, 1 => array $apiRequest).
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!)");
204 return [$resolveEvent->getApiProvider(), $apiRequest];
208 * Determine if the API request is allowed (under current policy)
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
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");
225 * Allow third-party code to manipulate the API request before execution.
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.
232 * [0 => ProviderInterface $provider, 1 => array $apiRequest]
233 * The revised API request.
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()];
242 * Allow third-party code to manipulate the API response after execution.
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.
251 * The revised $result.
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();
260 * @param int $version
265 public function getEntityNames($version) {
266 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
268 foreach ($this->getApiProviders() as $provider) {
269 /** @var \Civi\API\Provider\ProviderInterface $provider */
270 $entityNames = array_merge($entityNames, $provider->getEntityNames($version));
272 $entityNames = array_unique($entityNames);
278 * @param int $version
280 * @param string $entity
285 public function getActionNames($version, $entity) {
286 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
288 foreach ($this->getApiProviders() as $provider) {
289 /** @var \Civi\API\Provider\ProviderInterface $provider */
290 $actionNames = array_merge($actionNames, $provider->getActionNames($version, $entity));
292 $actionNames = array_unique($actionNames);
298 * @param \Exception $e
299 * An unhandled exception.
300 * @param array $apiRequest
301 * The full description of the API request.
305 * @throws \API_Exception
307 public function formatException($e, $apiRequest) {
309 if (!empty($apiRequest['params']['debug'])) {
310 $data['trace'] = $e->getTraceAsString();
312 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
316 * @param \API_Exception $e
317 * An unhandled exception.
318 * @param array $apiRequest
319 * The full description of the API request.
323 * @throws \API_Exception
325 public function formatApiException($e, $apiRequest) {
326 $data = $e->getExtraParams();
327 $data['entity'] = $apiRequest['entity'] ??
NULL;
328 $data['action'] = $apiRequest['action'] ??
NULL;
330 if (\CRM_Utils_Array
::value('debug', \CRM_Utils_Array
::value('params', $apiRequest))
332 && empty($data['trace'])
334 $data['trace'] = $e->getTraceAsString();
337 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
341 * @param \PEAR_Exception $e
342 * An unhandled exception.
343 * @param array $apiRequest
344 * The full description of the API request.
349 * @throws \API_Exception
351 public function formatPearException($e, $apiRequest) {
353 $error = $e->getCause();
354 if ($error instanceof \DB_Error
) {
355 $data['error_code'] = \DB
::errorMessage($error->getCode());
356 $data['sql'] = $error->getDebugInfo();
358 if (!empty($apiRequest['params']['debug'])) {
359 if (method_exists($e, 'getUserInfo')) {
360 $data['debug_info'] = $error->getUserInfo();
362 if (method_exists($e, 'getExtraData')) {
363 $data['debug_info'] = $data +
$error->getExtraData();
365 $data['trace'] = $e->getTraceAsString();
368 $data['tip'] = 'add debug=1 to your API call to have more info about the error';
371 return $this->createError($e->getMessage(), $data, $apiRequest);
376 * Descriptive error message.
379 * @param array $apiRequest
380 * The full description of the API request.
382 * Doesn't appear to be used.
384 * @throws \API_Exception
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') {
392 $fields = _civicrm_api3_api_getfields($apiRequest);
393 _civicrm_api3_validate_foreign_keys($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
395 catch (\Exception
$e) {
396 $msg = $e->getMessage();
400 $data = \
civicrm_api3_create_error($msg, $data);
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);
411 * @param array $apiRequest
412 * The full description of the API request.
413 * @param array $result
414 * The response to return to the client.
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;
423 if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) {
425 return $result['id'];
432 * @return array<ProviderInterface>
434 public function getApiProviders() {
435 return $this->apiProviders
;
439 * @param array $apiProviders
440 * Array<ProviderInterface>.
443 public function setApiProviders($apiProviders) {
444 $this->apiProviders
= $apiProviders;
449 * @param \Civi\API\Provider\ProviderInterface $apiProvider
450 * The API provider responsible for executing the request.
453 public function registerApiProvider($apiProvider) {
454 $this->apiProviders
[] = $apiProvider;
455 if ($apiProvider instanceof \Symfony\Component\EventDispatcher\EventSubscriberInterface
) {
456 $this->getDispatcher()->addSubscriber($apiProvider);
462 * @return \Symfony\Component\EventDispatcher\EventDispatcher
464 public function getDispatcher() {
465 return $this->dispatcher
;
469 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
470 * The event dispatcher which receives kernel events.
473 public function setDispatcher($dispatcher) {
474 $this->dispatcher
= $dispatcher;