3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 use Civi\API\Event\AuthorizeEvent
;
30 use Civi\API\Event\PrepareEvent
;
31 use Civi\API\Event\ExceptionEvent
;
32 use Civi\API\Event\ResolveEvent
;
33 use Civi\API\Event\RespondEvent
;
34 use Civi\API\Provider\ProviderInterface
;
38 * @copyright CiviCRM LLC (c) 2004-2017
43 * @var \Symfony\Component\EventDispatcher\EventDispatcher
45 protected $dispatcher;
48 * @var array<ProviderInterface>
50 protected $apiProviders;
53 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
54 * The event dispatcher which receives kernel events.
55 * @param array $apiProviders
56 * Array of ProviderInterface.
58 public function __construct($dispatcher, $apiProviders = array()) {
59 $this->apiProviders
= $apiProviders;
60 $this->dispatcher
= $dispatcher;
65 * @param string $entity
66 * Type of entities to deal with.
67 * @param string $action
68 * Create, get, delete or some special action name.
69 * @param array $params
70 * Array to be passed to API function.
76 public function run($entity, $action, $params, $extra = NULL) {
77 return $this->runSafe($entity, $action, $params, $extra);
81 * Parse and execute an API request. Any errors will be converted to
84 * @param string $entity
85 * Type of entities to deal with.
86 * @param string $action
87 * Create, get, delete or some special action name.
88 * @param array $params
89 * Array to be passed to API function.
94 * @throws \API_Exception
96 public function runSafe($entity, $action, $params, $extra = NULL) {
97 $apiRequest = Request
::create($entity, $action, $params, $extra);
100 $apiResponse = $this->runRequest($apiRequest);
101 return $this->formatResult($apiRequest, $apiResponse);
103 catch (\Exception
$e) {
104 $this->dispatcher
->dispatch(Events
::EXCEPTION
, new ExceptionEvent($e, NULL, $apiRequest, $this));
106 if ($e instanceof \PEAR_Exception
) {
107 $err = $this->formatPearException($e, $apiRequest);
109 elseif ($e instanceof \API_Exception
) {
110 $err = $this->formatApiException($e, $apiRequest);
113 $err = $this->formatException($e, $apiRequest);
116 return $this->formatResult($apiRequest, $err);
121 * Determine if a hypothetical API call would be authorized.
123 * @param string $entity
124 * Type of entities to deal with.
125 * @param string $action
126 * Create, get, delete or some special action name.
127 * @param array $params
128 * Array to be passed to function.
129 * @param mixed $extra
133 * TRUE if authorization would succeed.
136 public function runAuthorize($entity, $action, $params, $extra = NULL) {
138 $apiRequest = Request
::create($entity, $action, $params, $extra);
141 $this->boot($apiRequest);
142 list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
143 $this->authorize($apiProvider, $apiRequest);
146 catch (\Civi\API\Exception\UnauthorizedException
$e) {
152 * Execute an API request.
154 * The request must be in canonical format. Exceptions will be propagated out.
156 * @param array $apiRequest
158 * @throws \API_Exception
159 * @throws \Civi\API\Exception\NotImplementedException
160 * @throws \Civi\API\Exception\UnauthorizedException
162 public function runRequest($apiRequest) {
163 $this->boot($apiRequest);
164 $errorScope = \CRM_Core_TemporaryErrorScope
::useException();
166 list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
167 $this->authorize($apiProvider, $apiRequest);
168 $apiRequest = $this->prepare($apiProvider, $apiRequest);
169 $result = $apiProvider->invoke($apiRequest);
171 return $this->respond($apiProvider, $apiRequest, $result);
175 * Bootstrap - Load basic dependencies and sanity-check inputs.
177 * @param \Civi\API\V4\Action|array $apiRequest
178 * @throws \API_Exception
180 public function boot($apiRequest) {
181 require_once 'api/Exception.php';
183 if (!is_array($apiRequest['params'])) {
184 throw new \
API_Exception('Input variable `params` is not an array', 2000);
186 switch ($apiRequest['version']) {
189 require_once 'api/v3/utils.php';
190 _civicrm_api3_initialize();
198 throw new \
API_Exception('Unknown api version', 2000);
203 * @param array $apiRequest
204 * @throws \API_Exception
206 protected function validate($apiRequest) {
210 * Determine which, if any, service will execute the API request.
212 * @param array $apiRequest
213 * The full description of the API request.
214 * @throws Exception\NotImplementedException
216 * A tuple with the provider-object and a revised apiRequest.
217 * Array(0 => ProviderInterface, 1 => array $apiRequest).
219 public function resolve($apiRequest) {
220 /** @var ResolveEvent $resolveEvent */
221 $resolveEvent = $this->dispatcher
->dispatch(Events
::RESOLVE
, new ResolveEvent($apiRequest, $this));
222 $apiRequest = $resolveEvent->getApiRequest();
223 if (!$resolveEvent->getApiProvider()) {
224 throw new \Civi\API\Exception\
NotImplementedException("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
226 return array($resolveEvent->getApiProvider(), $apiRequest);
230 * Determine if the API request is allowed (under current policy)
232 * @param ProviderInterface $apiProvider
233 * The API provider responsible for executing the request.
234 * @param array $apiRequest
235 * The full description of the API request.
236 * @throws Exception\UnauthorizedException
238 public function authorize($apiProvider, $apiRequest) {
239 /** @var AuthorizeEvent $event */
240 $event = $this->dispatcher
->dispatch(Events
::AUTHORIZE
, new AuthorizeEvent($apiProvider, $apiRequest, $this));
241 if (!$event->isAuthorized()) {
242 throw new \Civi\API\Exception\
UnauthorizedException("Authorization failed");
247 * Allow third-party code to manipulate the API request before execution.
249 * @param ProviderInterface $apiProvider
250 * The API provider responsible for executing the request.
251 * @param array $apiRequest
252 * The full description of the API request.
254 * The revised API request.
256 public function prepare($apiProvider, $apiRequest) {
257 /** @var PrepareEvent $event */
258 $event = $this->dispatcher
->dispatch(Events
::PREPARE
, new PrepareEvent($apiProvider, $apiRequest, $this));
259 return $event->getApiRequest();
263 * Allow third-party code to manipulate the API response after execution.
265 * @param ProviderInterface $apiProvider
266 * The API provider responsible for executing the request.
267 * @param array $apiRequest
268 * The full description of the API request.
269 * @param array $result
270 * The response to return to the client.
272 * The revised $result.
274 public function respond($apiProvider, $apiRequest, $result) {
275 /** @var RespondEvent $event */
276 $event = $this->dispatcher
->dispatch(Events
::RESPOND
, new RespondEvent($apiProvider, $apiRequest, $result, $this));
277 return $event->getResponse();
281 * @param int $version
286 public function getEntityNames($version) {
287 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
288 $entityNames = array();
289 foreach ($this->getApiProviders() as $provider) {
290 /** @var ProviderInterface $provider */
291 $entityNames = array_merge($entityNames, $provider->getEntityNames($version));
293 $entityNames = array_unique($entityNames);
299 * @param int $version
301 * @param string $entity
306 public function getActionNames($version, $entity) {
307 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
308 $actionNames = array();
309 foreach ($this->getApiProviders() as $provider) {
310 /** @var ProviderInterface $provider */
311 $actionNames = array_merge($actionNames, $provider->getActionNames($version, $entity));
313 $actionNames = array_unique($actionNames);
319 * @param \Exception $e
320 * An unhandled exception.
321 * @param array $apiRequest
322 * The full description of the API request.
326 public function formatException($e, $apiRequest) {
328 if (!empty($apiRequest['params']['debug'])) {
329 $data['trace'] = $e->getTraceAsString();
331 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
335 * @param \API_Exception $e
336 * An unhandled exception.
337 * @param array $apiRequest
338 * The full description of the API request.
342 public function formatApiException($e, $apiRequest) {
343 $data = $e->getExtraParams();
344 $data['entity'] = \CRM_Utils_Array
::value('entity', $apiRequest);
345 $data['action'] = \CRM_Utils_Array
::value('action', $apiRequest);
347 if (\CRM_Utils_Array
::value('debug', \CRM_Utils_Array
::value('params', $apiRequest))
348 && empty($data['trace']) // prevent recursion
350 $data['trace'] = $e->getTraceAsString();
353 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
357 * @param \PEAR_Exception $e
358 * An unhandled exception.
359 * @param array $apiRequest
360 * The full description of the API request.
364 public function formatPearException($e, $apiRequest) {
366 $error = $e->getCause();
367 if ($error instanceof \DB_Error
) {
368 $data["error_code"] = \DB
::errorMessage($error->getCode());
369 $data["sql"] = $error->getDebugInfo();
371 if (!empty($apiRequest['params']['debug'])) {
372 if (method_exists($e, 'getUserInfo')) {
373 $data['debug_info'] = $error->getUserInfo();
375 if (method_exists($e, 'getExtraData')) {
376 $data['debug_info'] = $data +
$error->getExtraData();
378 $data['trace'] = $e->getTraceAsString();
381 $data['tip'] = "add debug=1 to your API call to have more info about the error";
384 return $this->createError($e->getMessage(), $data, $apiRequest);
389 * Descriptive error message.
392 * @param array $apiRequest
393 * The full description of the API request.
395 * Doesn't appear to be used.
397 * @throws \API_Exception
401 public function createError($msg, $data, $apiRequest, $code = NULL) {
402 // FIXME what to do with $code?
403 if ($msg == 'DB Error: constraint violation' ||
substr($msg, 0, 9) == 'DB Error:' ||
$msg == 'DB Error: already exists') {
405 $fields = _civicrm_api3_api_getfields($apiRequest);
406 _civicrm_api3_validate_foreign_keys($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
408 catch (\Exception
$e) {
409 $msg = $e->getMessage();
413 $data = civicrm_api3_create_error($msg, $data);
415 if (isset($apiRequest['params']) && is_array($apiRequest['params']) && !empty($apiRequest['params']['api.has_parent'])) {
416 $errorCode = empty($data['error_code']) ?
'chained_api_failed' : $data['error_code'];
417 throw new \
API_Exception('Error in call to ' . $apiRequest['entity'] . '_' . $apiRequest['action'] . ' : ' . $msg, $errorCode, $data);
424 * @param array $apiRequest
425 * The full description of the API request.
426 * @param array $result
427 * The response to return to the client.
430 public function formatResult($apiRequest, $result) {
431 if (isset($apiRequest, $apiRequest['params'])) {
432 if (isset($apiRequest['params']['format.is_success']) && $apiRequest['params']['format.is_success'] == 1) {
433 return (empty($result['is_error'])) ?
1 : 0;
436 if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) {
438 return $result['id'];
445 * @return array<ProviderInterface>
447 public function getApiProviders() {
448 return $this->apiProviders
;
452 * @param array $apiProviders
453 * Array<ProviderInterface>.
456 public function setApiProviders($apiProviders) {
457 $this->apiProviders
= $apiProviders;
462 * @param ProviderInterface $apiProvider
463 * The API provider responsible for executing the request.
466 public function registerApiProvider($apiProvider) {
467 $this->apiProviders
[] = $apiProvider;
468 if ($apiProvider instanceof \Symfony\Component\EventDispatcher\EventSubscriberInterface
) {
469 $this->getDispatcher()->addSubscriber($apiProvider);
475 * @return \Symfony\Component\EventDispatcher\EventDispatcher
477 public function getDispatcher() {
478 return $this->dispatcher
;
482 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
483 * The event dispatcher which receives kernel events.
486 public function setDispatcher($dispatcher) {
487 $this->dispatcher
= $dispatcher;