Merge branch 'angular-tests' of https://github.com/giant-rabbit/civicrm-core into...
[civicrm-core.git] / Civi / API / Kernel.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27 namespace Civi\API;
28
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;
35
36 /**
37 * @package Civi
38 * @copyright CiviCRM LLC (c) 2004-2014
39 */
40 class Kernel {
41
42 /**
43 * @var \Symfony\Component\EventDispatcher\EventDispatcher
44 */
45 protected $dispatcher;
46
47 /**
48 * @var array<ProviderInterface>
49 */
50 protected $apiProviders;
51
52 /**
53 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
54 * The event dispatcher which receives kernel events.
55 * @param array $apiProviders
56 * Array of ProviderInterface.
57 */
58 public function __construct($dispatcher, $apiProviders = array()) {
59 $this->apiProviders = $apiProviders;
60 $this->dispatcher = $dispatcher;
61 }
62
63 /**
64 * @param string $entity
65 * Type of entities to deal with.
66 * @param string $action
67 * Create, get, delete or some special action name.
68 * @param array $params
69 * Array to be passed to API function.
70 * @param mixed $extra
71 * Who knows.
72 *
73 * @return array|int
74 */
75 public function run($entity, $action, $params, $extra = NULL) {
76 /**
77 * @var $apiProvider \Civi\API\Provider\ProviderInterface|NULL
78 */
79 $apiProvider = NULL;
80
81 // TODO Define alternative calling convention makes it easier to construct $apiRequest
82 // without the ambiguity of "data" vs "options"
83 $apiRequest = Request::create($entity, $action, $params, $extra);
84
85 try {
86 if (!is_array($params)) {
87 throw new \API_Exception('Input variable `params` is not an array', 2000);
88 }
89
90 $this->boot();
91 $errorScope = \CRM_Core_TemporaryErrorScope::useException();
92
93 list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
94 $this->authorize($apiProvider, $apiRequest);
95 $apiRequest = $this->prepare($apiProvider, $apiRequest);
96 $result = $apiProvider->invoke($apiRequest);
97
98 $apiResponse = $this->respond($apiProvider, $apiRequest, $result);
99 return $this->formatResult($apiRequest, $apiResponse);
100 }
101 catch (\Exception $e) {
102 $this->dispatcher->dispatch(Events::EXCEPTION, new ExceptionEvent($e, $apiProvider, $apiRequest));
103
104 if ($e instanceof \PEAR_Exception) {
105 $err = $this->formatPearException($e, $apiRequest);
106 }
107 elseif ($e instanceof \API_Exception) {
108 $err = $this->formatApiException($e, $apiRequest);
109 }
110 else {
111 $err = $this->formatException($e, $apiRequest);
112 }
113
114 return $this->formatResult($apiRequest, $err);
115 }
116 }
117
118 /**
119 * Determine if a hypothetical API call would be authorized.
120 *
121 * @param string $entity
122 * Type of entities to deal with.
123 * @param string $action
124 * Create, get, delete or some special action name.
125 * @param array $params
126 * Array to be passed to function.
127 * @param mixed $extra
128 * Who knows.
129 * @return bool
130 * TRUE if authorization would succeed.
131 * @throws \Exception
132 */
133 public function runAuthorize($entity, $action, $params, $extra = NULL) {
134 $apiProvider = NULL;
135 $apiRequest = Request::create($entity, $action, $params, $extra);
136
137 try {
138 $this->boot();
139 list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
140 $this->authorize($apiProvider, $apiRequest);
141 return TRUE;
142 }
143 catch (\Civi\API\Exception\UnauthorizedException $e) {
144 return FALSE;
145 }
146 }
147
148 /**
149 * Bootstrap - Load basic dependencies.
150 */
151 public function boot() {
152 require_once 'api/v3/utils.php';
153 require_once 'api/Exception.php';
154 _civicrm_api3_initialize();
155 }
156
157 /**
158 * Determine which, if any, service will execute the API request.
159 *
160 * @param array $apiRequest
161 * The full description of the API request.
162 * @throws Exception\NotImplementedException
163 * @return array
164 * Array(0 => ProviderInterface, 1 => array).
165 */
166 public function resolve($apiRequest) {
167 /** @var ResolveEvent $resolveEvent */
168 $resolveEvent = $this->dispatcher->dispatch(Events::RESOLVE, new ResolveEvent($apiRequest));
169 $apiRequest = $resolveEvent->getApiRequest();
170 if (!$resolveEvent->getApiProvider()) {
171 throw new \Civi\API\Exception\NotImplementedException("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
172 }
173 return array($resolveEvent->getApiProvider(), $apiRequest);
174 }
175
176 /**
177 * Determine if the API request is allowed (under current policy)
178 *
179 * @param ProviderInterface $apiProvider
180 * The API provider responsible for executing the request.
181 * @param array $apiRequest
182 * The full description of the API request.
183 * @throws Exception\UnauthorizedException
184 */
185 public function authorize($apiProvider, $apiRequest) {
186 /** @var AuthorizeEvent $event */
187 $event = $this->dispatcher->dispatch(Events::AUTHORIZE, new AuthorizeEvent($apiProvider, $apiRequest));
188 if (!$event->isAuthorized()) {
189 throw new \Civi\API\Exception\UnauthorizedException("Authorization failed");
190 }
191 }
192
193 /**
194 * Allow third-party code to manipulate the API request before execution.
195 *
196 * @param ProviderInterface $apiProvider
197 * The API provider responsible for executing the request.
198 * @param array $apiRequest
199 * The full description of the API request.
200 * @return mixed
201 */
202 public function prepare($apiProvider, $apiRequest) {
203 /** @var PrepareEvent $event */
204 $event = $this->dispatcher->dispatch(Events::PREPARE, new PrepareEvent($apiProvider, $apiRequest));
205 return $event->getApiRequest();
206 }
207
208 /**
209 * Allow third-party code to manipulate the API response after execution.
210 *
211 * @param ProviderInterface $apiProvider
212 * The API provider responsible for executing the request.
213 * @param array $apiRequest
214 * The full description of the API request.
215 * @param array $result
216 * The response to return to the client.
217 * @return mixed
218 */
219 public function respond($apiProvider, $apiRequest, $result) {
220 /** @var RespondEvent $event */
221 $event = $this->dispatcher->dispatch(Events::RESPOND, new RespondEvent($apiProvider, $apiRequest, $result));
222 return $event->getResponse();
223 }
224
225 /**
226 * @param int $version
227 * API version.
228 * @return array
229 * Array<string>.
230 */
231 public function getEntityNames($version) {
232 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
233 $entityNames = array();
234 foreach ($this->getApiProviders() as $provider) {
235 /** @var ProviderInterface $provider */
236 $entityNames = array_merge($entityNames, $provider->getEntityNames($version));
237 }
238 $entityNames = array_unique($entityNames);
239 sort($entityNames);
240 return $entityNames;
241 }
242
243 /**
244 * @param int $version
245 * API version.
246 * @param string $entity
247 * API entity.
248 * @return array
249 * Array<string>
250 */
251 public function getActionNames($version, $entity) {
252 // Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
253 $actionNames = array();
254 foreach ($this->getApiProviders() as $provider) {
255 /** @var ProviderInterface $provider */
256 $actionNames = array_merge($actionNames, $provider->getActionNames($version, $entity));
257 }
258 $actionNames = array_unique($actionNames);
259 sort($actionNames);
260 return $actionNames;
261 }
262
263 /**
264 * @param \Exception $e
265 * An unhandled exception.
266 * @param array $apiRequest
267 * The full description of the API request.
268 * @return array
269 * API response.
270 */
271 public function formatException($e, $apiRequest) {
272 $data = array();
273 if (!empty($apiRequest['params']['debug'])) {
274 $data['trace'] = $e->getTraceAsString();
275 }
276 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
277 }
278
279 /**
280 * @param \API_Exception $e
281 * An unhandled exception.
282 * @param array $apiRequest
283 * The full description of the API request.
284 * @return array (API response)
285 */
286 public function formatApiException($e, $apiRequest) {
287 $data = $e->getExtraParams();
288 $data['entity'] = \CRM_Utils_Array::value('entity', $apiRequest);
289 $data['action'] = \CRM_Utils_Array::value('action', $apiRequest);
290
291 if (\CRM_Utils_Array::value('debug', \CRM_Utils_Array::value('params', $apiRequest))
292 && empty($data['trace']) // prevent recursion
293 ) {
294 $data['trace'] = $e->getTraceAsString();
295 }
296
297 return $this->createError($e->getMessage(), $data, $apiRequest, $e->getCode());
298 }
299
300 /**
301 * @param \PEAR_Exception $e
302 * An unhandled exception.
303 * @param array $apiRequest
304 * The full description of the API request.
305 * @return array
306 * API response.
307 */
308 public function formatPearException($e, $apiRequest) {
309 $data = array();
310 $error = $e->getCause();
311 if ($error instanceof \DB_Error) {
312 $data["error_code"] = \DB::errorMessage($error->getCode());
313 $data["sql"] = $error->getDebugInfo();
314 }
315 if (!empty($apiRequest['params']['debug'])) {
316 if (method_exists($e, 'getUserInfo')) {
317 $data['debug_info'] = $error->getUserInfo();
318 }
319 if (method_exists($e, 'getExtraData')) {
320 $data['debug_info'] = $data + $error->getExtraData();
321 }
322 $data['trace'] = $e->getTraceAsString();
323 }
324 else {
325 $data['tip'] = "add debug=1 to your API call to have more info about the error";
326 }
327
328 return $this->createError($e->getMessage(), $data, $apiRequest);
329 }
330
331 /**
332 * @param string $msg
333 * Descriptive error message.
334 * @param array $data
335 * Error data.
336 * @param array $apiRequest
337 * The full description of the API request.
338 * @param mixed $code
339 * Doesn't appear to be used.
340 *
341 * @throws \API_Exception
342 * @return array
343 * Array<type>.
344 */
345 public function createError($msg, $data, $apiRequest, $code = NULL) {
346 // FIXME what to do with $code?
347 if ($msg == 'DB Error: constraint violation' || substr($msg, 0, 9) == 'DB Error:' || $msg == 'DB Error: already exists') {
348 try {
349 $fields = _civicrm_api3_api_getfields($apiRequest);
350 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields, TRUE);
351 }
352 catch (\Exception $e) {
353 $msg = $e->getMessage();
354 }
355 }
356
357 $data = civicrm_api3_create_error($msg, $data);
358
359 if (isset($apiRequest['params']) && is_array($apiRequest['params']) && !empty($apiRequest['params']['api.has_parent'])) {
360 $errorCode = empty($data['error_code']) ? 'chained_api_failed' : $data['error_code'];
361 throw new \API_Exception('Error in call to ' . $apiRequest['entity'] . '_' . $apiRequest['action'] . ' : ' . $msg, $errorCode, $data);
362 }
363
364 return $data;
365 }
366
367 /**
368 * @param array $apiRequest
369 * The full description of the API request.
370 * @param array $result
371 * The response to return to the client.
372 * @return mixed
373 */
374 public function formatResult($apiRequest, $result) {
375 if (isset($apiRequest, $apiRequest['params'])) {
376 if (isset($apiRequest['params']['format.is_success']) && $apiRequest['params']['format.is_success'] == 1) {
377 return (empty($result['is_error'])) ? 1 : 0;
378 }
379
380 if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) {
381 // FIXME dispatch
382 return $result['id'];
383 }
384 }
385 return $result;
386 }
387
388 /**
389 * @return array<ProviderInterface>
390 */
391 public function getApiProviders() {
392 return $this->apiProviders;
393 }
394
395 /**
396 * @param array $apiProviders
397 * Array<ProviderInterface>.
398 * @return Kernel
399 */
400 public function setApiProviders($apiProviders) {
401 $this->apiProviders = $apiProviders;
402 return $this;
403 }
404
405 /**
406 * @param ProviderInterface $apiProvider
407 * The API provider responsible for executing the request.
408 * @return Kernel
409 */
410 public function registerApiProvider($apiProvider) {
411 $this->apiProviders[] = $apiProvider;
412 if ($apiProvider instanceof \Symfony\Component\EventDispatcher\EventSubscriberInterface) {
413 $this->getDispatcher()->addSubscriber($apiProvider);
414 }
415 return $this;
416 }
417
418 /**
419 * @return \Symfony\Component\EventDispatcher\EventDispatcher
420 */
421 public function getDispatcher() {
422 return $this->dispatcher;
423 }
424
425 /**
426 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
427 * The event dispatcher which receives kernel events.
428 * @return Kernel
429 */
430 public function setDispatcher($dispatcher) {
431 $this->dispatcher = $dispatcher;
432 return $this;
433 }
434 }