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(Events
::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);
145 $errorScope = \CRM_Core_TemporaryErrorScope
::useException();
147 list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
148 $this->authorize($apiProvider, $apiRequest);
149 list ($apiProvider, $apiRequest) = $this->prepare($apiProvider, $apiRequest);
150 $result = $apiProvider->invoke($apiRequest);
152 return $this->respond($apiProvider, $apiRequest, $result);
156 * Bootstrap - Load basic dependencies and sanity-check inputs.
158 * @param \Civi\Api4\Generic\AbstractAction|array $apiRequest
159 * @throws \API_Exception
161 public function boot($apiRequest) {
162 require_once 'api/Exception.php';
163 switch ($apiRequest['version']) {
165 if (!is_array($apiRequest['params'])) {
166 throw new \
API_Exception('Input variable `params` is not an array', 2000);
168 require_once 'api/v3/utils.php';
169 _civicrm_api3_initialize();
177 throw new \
API_Exception('Unknown api version', 2000);
182 * @param array $apiRequest
183 * @throws \API_Exception
185 protected function validate($apiRequest) {
189 * Determine which, if any, service will execute the API request.
191 * @param array $apiRequest
192 * The full description of the API request.
193 * @throws Exception\NotImplementedException
195 * A tuple with the provider-object and a revised apiRequest.
196 * Array(0 => ProviderInterface, 1 => array $apiRequest).
198 public function resolve($apiRequest) {
199 /** @var \Civi\API\Event\ResolveEvent $resolveEvent */
200 $resolveEvent = $this->dispatcher
->dispatch(Events
::RESOLVE
, new ResolveEvent($apiRequest, $this));
201 $apiRequest = $resolveEvent->getApiRequest();
202 if (!$resolveEvent->getApiProvider()) {
203 throw new \Civi\API\Exception\
NotImplementedException("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
205 return [$resolveEvent->getApiProvider(), $apiRequest];
209 * Determine if the API request is allowed (under current policy)
211 * @param \Civi\API\Provider\ProviderInterface $apiProvider
212 * The API provider responsible for executing the request.
213 * @param array $apiRequest
214 * The full description of the API request.
215 * @throws Exception\UnauthorizedException
217 public function authorize($apiProvider, $apiRequest) {
218 /** @var \Civi\API\Event\AuthorizeEvent $event */
219 $event = $this->dispatcher
->dispatch(Events
::AUTHORIZE
, new AuthorizeEvent($apiProvider, $apiRequest, $this));
220 if (!$event->isAuthorized()) {
221 throw new \Civi\API\Exception\
UnauthorizedException("Authorization failed");
226 * Allow third-party code to manipulate the API request before execution.
228 * @param \Civi\API\Provider\ProviderInterface $apiProvider
229 * The API provider responsible for executing the request.
230 * @param array $apiRequest
231 * The full description of the API request.
233 * [0 => ProviderInterface $provider, 1 => array $apiRequest]
234 * The revised API request.
236 public function prepare($apiProvider, $apiRequest) {
237 /** @var \Civi\API\Event\PrepareEvent $event */
238 $event = $this->dispatcher
->dispatch(Events
::PREPARE
, new PrepareEvent($apiProvider, $apiRequest, $this));
239 return [$event->getApiProvider(), $event->getApiRequest()];
243 * Allow third-party code to manipulate the API response after execution.
245 * @param \Civi\API\Provider\ProviderInterface $apiProvider
246 * The API provider responsible for executing the request.
247 * @param array $apiRequest
248 * The full description of the API request.
249 * @param array $result
250 * The response to return to the client.
252 * The revised $result.
254 public function respond($apiProvider, $apiRequest, $result) {
255 /** @var \Civi\API\Event\RespondEvent $event */
256 $event = $this->dispatcher
->dispatch(Events
::RESPOND
, new RespondEvent($apiProvider, $apiRequest, $result, $this));
257 return $event->getResponse();
261 * @param int $version
266 public function getEntityNames($version) {
267 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
269 foreach ($this->getApiProviders() as $provider) {
270 /** @var \Civi\API\Provider\ProviderInterface $provider */
271 $entityNames = array_merge($entityNames, $provider->getEntityNames($version));
273 $entityNames = array_unique($entityNames);
279 * @param int $version
281 * @param string $entity
286 public function getActionNames($version, $entity) {
287 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
289 foreach ($this->getApiProviders() as $provider) {
290 /** @var \Civi\API\Provider\ProviderInterface $provider */
291 $actionNames = array_merge($actionNames, $provider->getActionNames($version, $entity));
293 $actionNames = array_unique($actionNames);
299 * @param \Exception $e
300 * An unhandled exception.
301 * @param array $apiRequest
302 * The full description of the API request.
306 * @throws \API_Exception
308 public function formatException($e, $apiRequest) {
310 if (!empty($apiRequest['params']['debug'])) {
311 $data['trace'] = $e->getTraceAsString();
313 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
317 * @param \API_Exception $e
318 * An unhandled exception.
319 * @param array $apiRequest
320 * The full description of the API request.
324 * @throws \API_Exception
326 public function formatApiException($e, $apiRequest) {
327 $data = $e->getExtraParams();
328 $data['entity'] = \CRM_Utils_Array
::value('entity', $apiRequest);
329 $data['action'] = \CRM_Utils_Array
::value('action', $apiRequest);
331 if (\CRM_Utils_Array
::value('debug', \CRM_Utils_Array
::value('params', $apiRequest))
333 && empty($data['trace'])
335 $data['trace'] = $e->getTraceAsString();
338 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
342 * @param \PEAR_Exception $e
343 * An unhandled exception.
344 * @param array $apiRequest
345 * The full description of the API request.
350 * @throws \API_Exception
352 public function formatPearException($e, $apiRequest) {
354 $error = $e->getCause();
355 if ($error instanceof \DB_Error
) {
356 $data['error_code'] = \DB
::errorMessage($error->getCode());
357 $data['sql'] = $error->getDebugInfo();
359 if (!empty($apiRequest['params']['debug'])) {
360 if (method_exists($e, 'getUserInfo')) {
361 $data['debug_info'] = $error->getUserInfo();
363 if (method_exists($e, 'getExtraData')) {
364 $data['debug_info'] = $data +
$error->getExtraData();
366 $data['trace'] = $e->getTraceAsString();
369 $data['tip'] = 'add debug=1 to your API call to have more info about the error';
372 return $this->createError($e->getMessage(), $data, $apiRequest);
377 * Descriptive error message.
380 * @param array $apiRequest
381 * The full description of the API request.
383 * Doesn't appear to be used.
385 * @throws \API_Exception
389 public function createError($msg, $data, $apiRequest, $code = NULL) {
390 // FIXME what to do with $code?
391 if ($msg === 'DB Error: constraint violation' ||
substr($msg, 0, 9) == 'DB Error:' ||
$msg == 'DB Error: already exists') {
393 $fields = _civicrm_api3_api_getfields($apiRequest);
394 _civicrm_api3_validate_foreign_keys($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
396 catch (\Exception
$e) {
397 $msg = $e->getMessage();
401 $data = \
civicrm_api3_create_error($msg, $data);
403 if (isset($apiRequest['params']) && is_array($apiRequest['params']) && !empty($apiRequest['params']['api.has_parent'])) {
404 $errorCode = empty($data['error_code']) ?
'chained_api_failed' : $data['error_code'];
405 throw new \
API_Exception('Error in call to ' . $apiRequest['entity'] . '_' . $apiRequest['action'] . ' : ' . $msg, $errorCode, $data);
412 * @param array $apiRequest
413 * The full description of the API request.
414 * @param array $result
415 * The response to return to the client.
418 public function formatResult($apiRequest, $result) {
419 if (isset($apiRequest, $apiRequest['params'])) {
420 if (isset($apiRequest['params']['format.is_success']) && $apiRequest['params']['format.is_success'] == 1) {
421 return (empty($result['is_error'])) ?
1 : 0;
424 if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) {
426 return $result['id'];
433 * @return array<ProviderInterface>
435 public function getApiProviders() {
436 return $this->apiProviders
;
440 * @param array $apiProviders
441 * Array<ProviderInterface>.
444 public function setApiProviders($apiProviders) {
445 $this->apiProviders
= $apiProviders;
450 * @param \Civi\API\Provider\ProviderInterface $apiProvider
451 * The API provider responsible for executing the request.
454 public function registerApiProvider($apiProvider) {
455 $this->apiProviders
[] = $apiProvider;
456 if ($apiProvider instanceof \Symfony\Component\EventDispatcher\EventSubscriberInterface
) {
457 $this->getDispatcher()->addSubscriber($apiProvider);
463 * @return \Symfony\Component\EventDispatcher\EventDispatcher
465 public function getDispatcher() {
466 return $this->dispatcher
;
470 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
471 * The event dispatcher which receives kernel events.
474 public function setDispatcher($dispatcher) {
475 $this->dispatcher
= $dispatcher;