3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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
;
39 * @copyright CiviCRM LLC (c) 2004-2013
45 * @var \Symfony\Component\EventDispatcher\EventDispatcher
47 protected $dispatcher;
50 * @var array<ProviderInterface>
52 protected $apiProviders;
54 function __construct($dispatcher, $apiProviders = array()) {
55 $this->apiProviders
= $apiProviders;
56 $this->dispatcher
= $dispatcher;
60 * @param string $entity
61 * type of entities to deal with
62 * @param string $action
63 * create, get, delete or some special action name.
64 * @param array $params
65 * array to be passed to function
70 public function run($entity, $action, $params, $extra = NULL) {
72 * @var $apiProvider \Civi\API\Provider\ProviderInterface|NULL
76 // TODO Define alternative calling convention makes it easier to construct $apiRequest
77 // without the ambiguity of "data" vs "options"
78 $apiRequest = Request
::create($entity, $action, $params, $extra);
81 if (!is_array($params)) {
82 throw new \
API_Exception('Input variable `params` is not an array', 2000);
86 $errorScope = \CRM_Core_TemporaryErrorScope
::useException();
88 list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
89 $this->authorize($apiProvider, $apiRequest);
90 $apiRequest = $this->prepare($apiProvider, $apiRequest);
91 $result = $apiProvider->invoke($apiRequest);
93 $apiResponse = $this->respond($apiProvider, $apiRequest, $result);
94 return $this->formatResult($apiRequest, $apiResponse);
96 catch (\Exception
$e) {
97 $this->dispatcher
->dispatch(Events
::EXCEPTION
, new ExceptionEvent($e, $apiProvider, $apiRequest));
99 if ($e instanceof \PEAR_Exception
) {
100 $err = $this->formatPearException($e, $apiRequest);
101 } elseif ($e instanceof \API_Exception
) {
102 $err = $this->formatApiException($e, $apiRequest);
104 $err = $this->formatException($e, $apiRequest);
107 return $this->formatResult($apiRequest, $err);
111 public function boot() {
112 require_once ('api/v3/utils.php');
113 require_once 'api/Exception.php';
114 _civicrm_api3_initialize();
118 * Determine which, if any, service will execute the API request.
120 * @param array $apiRequest
121 * @throws Exception\NotImplementedException
124 public function resolve($apiRequest) {
125 /** @var ResolveEvent $resolveEvent */
126 $resolveEvent = $this->dispatcher
->dispatch(Events
::RESOLVE
, new ResolveEvent($apiRequest));
127 $apiRequest = $resolveEvent->getApiRequest();
128 if (!$resolveEvent->getApiProvider()) {
129 throw new \Civi\API\Exception\
NotImplementedException("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
131 return array($resolveEvent->getApiProvider(), $apiRequest);
135 * Determine if the API request is allowed (under current policy)
137 * @param ProviderInterface $apiProvider
138 * @param array $apiRequest
139 * @throws Exception\UnauthorizedException
141 public function authorize($apiProvider, $apiRequest) {
142 /** @var AuthorizeEvent $event */
143 $event = $this->dispatcher
->dispatch(Events
::AUTHORIZE
, new AuthorizeEvent($apiProvider, $apiRequest));
144 if (!$event->isAuthorized()) {
145 throw new \Civi\API\Exception\
UnauthorizedException("Authorization failed");
150 * Allow third-party code to manipulate the API request before execution.
152 * @param ProviderInterface $apiProvider
153 * @param array $apiRequest
156 public function prepare($apiProvider, $apiRequest) {
157 /** @var PrepareEvent $event */
158 $event = $this->dispatcher
->dispatch(Events
::PREPARE
, new PrepareEvent($apiProvider, $apiRequest));
159 return $event->getApiRequest();
163 * Allow third-party code to manipulate the API response after execution.
165 * @param ProviderInterface $apiProvider
166 * @param array $apiRequest
167 * @param array $result
170 public function respond($apiProvider, $apiRequest, $result) {
171 /** @var RespondEvent $event */
172 $event = $this->dispatcher
->dispatch(Events
::RESPOND
, new RespondEvent($apiProvider, $apiRequest, $result));
173 return $event->getResponse();
177 * @param int $version
178 * @return array<string>
180 public function getEntityNames($version) {
181 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
182 $entityNames = array();
183 foreach ($this->getApiProviders() as $provider) {
184 /** @var ProviderInterface $provider */
185 $entityNames = array_merge($entityNames, $provider->getEntityNames($version));
187 $entityNames = array_unique($entityNames);
193 * @param int $version
194 * @param string $entity
195 * @return array<string>
197 public function getActionNames($version, $entity) {
198 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
199 $actionNames = array();
200 foreach ($this->getApiProviders() as $provider) {
201 /** @var ProviderInterface $provider */
202 $actionNames = array_merge($actionNames, $provider->getActionNames($version, $entity));
204 $actionNames = array_unique($actionNames);
210 * @param \Exception $e
211 * @param array $apiRequest
212 * @return array (API response)
214 public function formatException($e, $apiRequest) {
216 if (!empty($apiRequest['params']['debug'])) {
217 $data['trace'] = $e->getTraceAsString();
219 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
223 * @param \API_Exception $e
224 * @param array $apiRequest
225 * @return array (API response)
227 public function formatApiException($e, $apiRequest) {
228 $data = $e->getExtraParams();
229 $data['entity'] = \CRM_Utils_Array
::value('entity', $apiRequest);
230 $data['action'] = \CRM_Utils_Array
::value('action', $apiRequest);
232 if (\CRM_Utils_Array
::value('debug', \CRM_Utils_Array
::value('params', $apiRequest))
233 && empty($data['trace']) // prevent recursion
235 $data['trace'] = $e->getTraceAsString();
238 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
242 * @param \PEAR_Exception $e
243 * @param array $apiRequest
244 * @return array (API response)
246 public function formatPearException($e, $apiRequest) {
248 $error = $e->getCause();
249 if ($error instanceof \DB_Error
) {
250 $data["error_code"] = \DB
::errorMessage($error->getCode());
251 $data["sql"] = $error->getDebugInfo();
253 if (!empty($apiRequest['params']['debug'])) {
254 if (method_exists($e, 'getUserInfo')) {
255 $data['debug_info'] = $error->getUserInfo();
257 if (method_exists($e, 'getExtraData')) {
258 $data['debug_info'] = $data +
$error->getExtraData();
260 $data['trace'] = $e->getTraceAsString();
263 $data['tip'] = "add debug=1 to your API call to have more info about the error";
266 return $this->createError($e->getMessage(), $data, $apiRequest);
273 * @param array $apiRequest
274 * @param mixed $code doesn't appear to be used
276 * @throws \API_Exception
277 * @return array <type>
279 function createError($msg, $data, $apiRequest, $code = NULL) {
280 // FIXME what to do with $code?
281 if ($msg == 'DB Error: constraint violation' ||
substr($msg, 0, 9) == 'DB Error:' ||
$msg == 'DB Error: already exists') {
283 $fields = _civicrm_api3_api_getfields($apiRequest);
284 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields, TRUE);
285 } catch (\Exception
$e) {
286 $msg = $e->getMessage();
290 $data = civicrm_api3_create_error($msg, $data);
292 if (isset($apiRequest['params']) && is_array($apiRequest['params']) && !empty($apiRequest['params']['api.has_parent'])) {
293 $errorCode = empty($data['error_code']) ?
'chained_api_failed' : $data['error_code'];
294 throw new \
API_Exception('Error in call to ' . $apiRequest['entity'] . '_' . $apiRequest['action'] . ' : ' . $msg, $errorCode, $data);
301 * @param array $apiRequest
302 * @param array $result
305 public function formatResult($apiRequest, $result) {
306 if (isset($apiRequest, $apiRequest['params'])) {
307 if (isset($apiRequest['params']['format.is_success']) && $apiRequest['params']['format.is_success'] == 1) {
308 return (empty($result['is_error'])) ?
1 : 0;
311 if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) {
313 return $result['id'];
320 * @return array<ProviderInterface>
322 public function getApiProviders() {
323 return $this->apiProviders
;
327 * @param array $apiProviders
330 public function setApiProviders($apiProviders) {
331 $this->apiProviders
= $apiProviders;
336 * @param ProviderInterface $apiProvider
339 public function registerApiProvider($apiProvider) {
340 $this->apiProviders
[] = $apiProvider;
341 if ($apiProvider instanceof \Symfony\Component\EventDispatcher\EventSubscriberInterface
) {
342 $this->getDispatcher()->addSubscriber($apiProvider);
348 * @return \Symfony\Component\EventDispatcher\EventDispatcher
350 public function getDispatcher() {
351 return $this->dispatcher
;
355 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
358 public function setDispatcher($dispatcher) {
359 $this->dispatcher
= $dispatcher;