Spaces:
No application file
No application file
File size: 23,240 Bytes
d2897cd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 |
<?php
namespace Mautic\ApiBundle\Controller;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Doctrine\Persistence\ManagerRegistry;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\View\View;
use JMS\Serializer\Exclusion\ExclusionStrategyInterface;
use Mautic\ApiBundle\ApiEvents;
use Mautic\ApiBundle\Event\ApiSerializationContextEvent;
use Mautic\ApiBundle\Helper\BatchIdToEntityHelper;
use Mautic\ApiBundle\Helper\EntityResultHelper;
use Mautic\ApiBundle\Serializer\Exclusion\ParentChildrenExclusionStrategy;
use Mautic\ApiBundle\Serializer\Exclusion\PublishDetailsExclusionStrategy;
use Mautic\CoreBundle\Controller\FormErrorMessagesTrait;
use Mautic\CoreBundle\Controller\MauticController;
use Mautic\CoreBundle\Factory\MauticFactory;
use Mautic\CoreBundle\Factory\ModelFactory;
use Mautic\CoreBundle\Form\RequestTrait;
use Mautic\CoreBundle\Helper\AppVersion;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\InputHelper;
use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\CoreBundle\Model\AbstractCommonModel;
use Mautic\CoreBundle\Model\MauticModelInterface;
use Mautic\CoreBundle\Security\Exception\PermissionException;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use Mautic\CoreBundle\Translation\Translator;
use Mautic\UserBundle\Entity\User;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
/**
* @template E of object
*/
class FetchCommonApiController extends AbstractFOSRestController implements MauticController
{
use RequestTrait;
use FormErrorMessagesTrait;
/**
* If set to true, serializer will not return null values.
*
* @var bool
*/
protected $customSelectRequested = false;
/**
* Class for the entity.
*
* @var class-string<E>
*/
protected $entityClass;
/**
* Key to return for entity lists.
*
* @var string
*/
protected $entityNameMulti;
/**
* Key to return for a single entity.
*
* @var string
*/
protected $entityNameOne;
/**
* Custom JMS strategies to add to the view's context.
*
* @var array<int, ExclusionStrategyInterface>
*/
protected $exclusionStrategies = [];
/**
* Pass to the model's getEntities() method.
*
* @var array<mixed>
*/
protected $extraGetEntitiesArguments = [];
/**
* @var bool
*/
protected $inBatchMode = false;
/**
* Used to set default filters for entity lists such as restricting to owning user.
*
* @var array<array<string, mixed>>
*/
protected $listFilters = [];
/**
* Model object for processing the entity.
*
* @var AbstractCommonModel<E>|null
*/
protected $model;
/**
* The level parent/children should stop loading if applicable.
*
* @var int
*/
protected $parentChildrenLevelDepth = 3;
/**
* Permission base for the entity such as page:pages.
*
* @var string|null
*/
protected $permissionBase;
/**
* @var array<int, string>
*/
protected $serializerGroups = [];
/**
* @var Translator
*/
protected $translator;
protected ContainerBagInterface $parametersContainer;
/**
* @param ModelFactory<E> $modelFactory
*/
public function __construct(
protected CorePermissions $security,
Translator $translator,
protected EntityResultHelper $entityResultHelper,
private AppVersion $appVersion,
private RequestStack $requestStack,
protected ManagerRegistry $doctrine,
protected ModelFactory $modelFactory,
protected EventDispatcherInterface $dispatcher,
protected CoreParametersHelper $coreParametersHelper,
protected MauticFactory $factory,
) {
$this->translator = $translator;
if (null !== $this->model && !$this->permissionBase && method_exists($this->model, 'getPermissionBase')) {
$this->permissionBase = $this->model->getPermissionBase();
}
}
/**
* Obtains a list of entities as defined by the API URL.
*
* @return Response
*/
public function getEntitiesAction(Request $request, UserHelper $userHelper)
{
$repo = $this->model->getRepository();
$tableAlias = $repo->getTableAlias();
$publishedOnly = $request->get('published', 0);
$minimal = $request->get('minimal', 0);
try {
if (!$this->security->isGranted($this->permissionBase.':view')) {
return $this->accessDenied();
}
} catch (PermissionException $e) {
return $this->accessDenied($e->getMessage());
}
if ($this->security->checkPermissionExists($this->permissionBase.':viewother')
&& !$this->security->isGranted($this->permissionBase.':viewother')
&& null !== $user = $userHelper->getUser()
) {
$this->listFilters[] = [
'column' => $tableAlias.'.createdBy',
'expr' => 'eq',
'value' => $user->getId(),
];
}
if ($publishedOnly) {
$this->listFilters[] = [
'column' => $tableAlias.'.isPublished',
'expr' => 'eq',
'value' => true,
];
}
if ($minimal) {
if (isset($this->serializerGroups[0])) {
$this->serializerGroups[0] = str_replace('Details', 'List', $this->serializerGroups[0]);
}
}
$args = array_merge(
[
'start' => $request->query->get('start', 0),
'limit' => $request->query->get('limit', $this->coreParametersHelper->get('default_pagelimit')),
'filter' => [
'string' => $request->query->get('search', ''),
'force' => $this->listFilters,
],
'orderBy' => $this->addAliasIfNotPresent($request->query->get('orderBy', ''), $tableAlias),
'orderByDir' => $request->query->get('orderByDir', 'ASC'),
'withTotalCount' => true, // for repositories that break free of Paginator
],
$this->extraGetEntitiesArguments
);
if ($select = InputHelper::cleanArray($request->get('select', []))) {
$args['select'] = $select;
$this->customSelectRequested = true;
}
if ($where = $this->getWhereFromRequest($request)) {
$args['filter']['where'] = $where;
}
if ($order = $this->getOrderFromRequest($request)) {
$args['filter']['order'] = $order;
}
if ($totalCountTtl = $this->getTotalCountTtl()) {
$args['totalCountTtl'] = $totalCountTtl;
}
$results = $this->model->getEntities($args);
[$entities, $totalCount] = $this->prepareEntitiesForView($results);
$view = $this->view(
[
'total' => $totalCount,
$this->entityNameMulti => $entities,
],
Response::HTTP_OK
);
$this->setSerializationContext($view);
return $this->handleView($view);
}
/**
* Sanitizes and returns an array of where statements from the request.
*
* @return array<mixed>
*/
protected function getWhereFromRequest(Request $request)
{
$where = InputHelper::cleanArray($request->get('where', []));
$this->sanitizeWhereClauseArrayFromRequest($where);
return $where;
}
/**
* Sanitizes and returns an array of ORDER statements from the request.
*
* @return array<mixed>
*/
protected function getOrderFromRequest(Request $request): array
{
return InputHelper::cleanArray($request->get('order', []));
}
/**
* Adds the repository alias to the column name if it doesn't exist.
*
* @return string $column name with alias prefix
*/
protected function addAliasIfNotPresent(string $columns, string $alias): string
{
if (!$columns) {
return $columns;
}
$columns = explode(',', trim($columns));
$prefix = $alias.'.';
array_walk(
$columns,
function (&$column, $key, $prefix): void {
$column = trim($column);
if (1 === count(explode('.', $column))) {
$column = $prefix.$column;
}
},
$prefix
);
return implode(',', $columns);
}
/**
* Obtains a specific entity as defined by the API URL.
*
* @param int $id Entity ID
*
* @return Response
*/
public function getEntityAction(Request $request, $id)
{
$args = [];
if ($select = InputHelper::cleanArray($request->get('select', []))) {
$args['select'] = $select;
$this->customSelectRequested = true;
}
if (!empty($args)) {
$args['id'] = $id;
$entity = $this->model->getEntity($args);
} else {
$entity = $this->model->getEntity($id);
}
if (!$entity instanceof $this->entityClass) {
return $this->notFound();
}
if (!$this->checkEntityAccess($entity)) {
return $this->accessDenied();
}
$this->preSerializeEntity($entity);
$view = $this->view([$this->entityNameOne => $entity], Response::HTTP_OK);
$this->setSerializationContext($view);
return $this->handleView($view);
}
/**
* Creates new entity from provided params.
*
* @param array<mixed> $params
*
* @return object
*/
public function getNewEntity(array $params)
{
return $this->model->getEntity();
}
public function getCurrentRequest(): Request
{
$request = $this->requestStack->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('Request is not set.');
}
return $request;
}
/**
* Alias for notFound method. It's used in the LeadAccessTrait.
*
* @param array<mixed> $args
*
* @return Response
*/
public function postActionRedirect(array $args = [])
{
return $this->notFound('mautic.contact.error.notfound');
}
/**
* Returns a 403 Access Denied.
*
* @param string $msg
*
* @return Response
*/
protected function accessDenied($msg = 'mautic.core.error.accessdenied')
{
return $this->returnError($msg, Response::HTTP_FORBIDDEN);
}
protected function addExclusionStrategy(ExclusionStrategyInterface $strategy): void
{
$this->exclusionStrategies[] = $strategy;
}
/**
* Returns a 400 Bad Request.
*
* @param string $msg
*
* @return Response
*/
protected function badRequest($msg = 'mautic.core.error.badrequest')
{
return $this->returnError($msg, Response::HTTP_BAD_REQUEST);
}
/**
* Checks if user has permission to access retrieved entity.
*
* @param mixed $entity
* @param string $action view|create|edit|publish|delete
*
* @return bool|Response
*/
protected function checkEntityAccess($entity, $action = 'view')
{
if ('create' !== $action && is_object($entity) && method_exists($entity, 'getCreatedBy')) {
$ownPerm = "{$this->permissionBase}:{$action}own";
$otherPerm = "{$this->permissionBase}:{$action}other";
$owner = (method_exists($entity, 'getPermissionUser')) ? $entity->getPermissionUser() : $entity->getCreatedBy();
return $this->security->hasEntityAccess($ownPerm, $otherPerm, $owner);
}
try {
return $this->security->isGranted("{$this->permissionBase}:{$action}");
} catch (PermissionException $e) {
return $this->accessDenied($e->getMessage());
}
}
/**
* @param mixed[] $parameters
* @param mixed[] $errors
* @param bool $prepareForSerialization
* @param string $requestIdColumn
* @param MauticModelInterface|null $model
* @param bool $returnWithOriginalKeys
*
* @return mixed[]
*/
protected function getBatchEntities($parameters, &$errors, $prepareForSerialization = false, $requestIdColumn = 'id', $model = null, $returnWithOriginalKeys = true): array
{
$idHelper = new BatchIdToEntityHelper($parameters, $requestIdColumn);
if (!$idHelper->hasIds()) {
return [];
}
/** @var AbstractCommonModel<object> $model */
$model = $model ?: $this->model;
$entities = $model->getEntities(
[
'filter' => [
'force' => [
[
'column' => $model->getRepository()->getTableAlias().'.id',
'expr' => 'in',
'value' => $idHelper->getIds(),
],
],
],
'ignore_paginator' => true,
]
);
// It must be associative because the order of entities has changed
$idHelper->setIsAssociative(true);
[$entities, $total] = $prepareForSerialization
?
$this->prepareEntitiesForView($entities)
:
$this->prepareEntityResultsToArray($entities);
// Set errors
if ($idHelper->hasErrors()) {
foreach ($idHelper->getErrors() as $key => $error) {
$this->setBatchError($key, $error, Response::HTTP_BAD_REQUEST, $errors);
}
}
// Return the response with matching keys from the request
if ($returnWithOriginalKeys) {
if ($entities instanceof \ArrayObject) {
$entities = $entities->getArrayCopy();
}
return $idHelper->orderByOriginalKey($entities);
}
// Return the response with IDs as keys (default behavior)
$return = [];
foreach ($entities as $entity) {
$return[$entity->getId()] = $entity;
}
return $return;
}
/**
* Get the default properties of an entity and parents.
*
* @phpstan-param E $entity
*
* @return array<mixed>
*/
protected function getEntityDefaultProperties(object $entity): array
{
$class = $entity::class;
$chain = array_reverse(class_parents($entity), true) + [$class => $class];
$defaultValues = [];
$classMetdata = new ClassMetadata($class);
foreach ($chain as $class) {
if (method_exists($class, 'loadMetadata')) {
$class::loadMetadata($classMetdata);
}
$defaultValues += (new \ReflectionClass($class))->getDefaultProperties();
}
// These are the mapped columns
$fields = $classMetdata->getFieldNames();
// Merge values in with $fields
$properties = [];
foreach ($fields as $field) {
$properties[$field] = $defaultValues[$field];
}
return $properties;
}
/**
* Append options to the form.
*
* @return array<string, mixed>
*/
protected function getEntityFormOptions(): array
{
return [];
}
/**
* Get a model instance from the service container.
*
* @return AbstractCommonModel<E>
*/
protected function getModel(string $modelNameKey): AbstractCommonModel
{
return $this->modelFactory->getModel($modelNameKey);
}
/**
* Returns a 404 Not Found.
*
* @return Response
*/
protected function notFound(string $msg = 'mautic.core.error.notfound')
{
return $this->returnError($msg, Response::HTTP_NOT_FOUND);
}
/**
* Gives child controllers opportunity to analyze and do whatever to an entity before going through serializer.
*
* @phpstan-param E $entity
*/
protected function preSerializeEntity(object $entity, string $action = 'view'): void
{
}
/**
* Prepares entities returned from repository getEntities().
*
* @param array<mixed>|Paginator<E> $results
*
* @return array{0: array<mixed>|\ArrayObject<int,mixed>, 1: int}
*/
protected function prepareEntitiesForView($results): array
{
return $this->prepareEntityResultsToArray(
$results,
function ($entity): void {
$this->preSerializeEntity($entity);
}
);
}
/**
* @param array<mixed>|Paginator<E> $results
* @param callable|null $callback
*
* @return array{0: array<mixed>|\ArrayObject<int,mixed>, 1: int}
*/
protected function prepareEntityResultsToArray($results, $callback = null): array
{
if (is_array($results) && isset($results['count'])) {
$totalCount = $results['count'];
$results = $results['results'];
} else {
$totalCount = count($results);
}
$entities = $this->entityResultHelper->getArray($results, $callback);
return [$entities, $totalCount];
}
/**
* Returns an error.
*
* @param array<mixed> $details
*
* @return Response|array<string, array<mixed>|int|string|null>
*/
protected function returnError(string $msg, int $code = Response::HTTP_INTERNAL_SERVER_ERROR, array $details = [])
{
if ($this->translator->hasId($msg, 'flashes')) {
$msg = $this->translator->trans($msg, [], 'flashes');
} elseif ($this->translator->hasId($msg, 'messages')) {
$msg = $this->translator->trans($msg, [], 'messages');
}
$error = [
'code' => $code,
'message' => $msg,
'details' => $details,
'type' => null,
];
if ($this->inBatchMode) {
return $error;
}
$view = $this->view(
[
'errors' => [
$error,
],
],
$code
);
return $this->handleView($view);
}
/**
* @param array<mixed> $where
*/
protected function sanitizeWhereClauseArrayFromRequest(array &$where): void
{
foreach ($where as $key => $statement) {
if (isset($statement['internal'])) {
unset($where[$key]);
} elseif (in_array($statement['expr'], ['andX', 'orX'])) {
$this->sanitizeWhereClauseArrayFromRequest($statement['val']);
}
}
}
/**
* @param array<int, array<string|int>> $errors
* @param array<int, object|null> $entities
*
* @phpstan-param E|null $entity
* @phpstan-param array<int, E|null> $entities
*/
protected function setBatchError(int $key, string $msg, int $code, array &$errors, array &$entities = [], ?object $entity = null): void
{
unset($entities[$key]);
if ($entity) {
$this->doctrine->getManager()->detach($entity);
}
$errors[$key] = [
'message' => $this->translator->hasId($msg, 'flashes') ? $this->translator->trans($msg, [], 'flashes') : $msg,
'code' => $code,
'type' => 'api',
];
}
/**
* Set serialization groups and exclusion strategies.
*/
protected function setSerializationContext(View $view): void
{
$context = $view->getContext();
if ($this->dispatcher->hasListeners(ApiEvents::API_PRE_SERIALIZATION_CONTEXT)) {
$apiSerializationContextEvent = new ApiSerializationContextEvent($context, $this->getCurrentRequest());
$this->dispatcher->dispatch($apiSerializationContextEvent, ApiEvents::API_PRE_SERIALIZATION_CONTEXT);
$context = $apiSerializationContextEvent->getContext();
}
if (!empty($this->serializerGroups)) {
$context->setGroups($this->serializerGroups);
}
// Only include FormEntity properties for the top level entity and not the associated entities
$context->addExclusionStrategy(
new PublishDetailsExclusionStrategy()
);
// Only include first level of children/parents
if ($this->parentChildrenLevelDepth) {
$context->addExclusionStrategy(
new ParentChildrenExclusionStrategy($this->parentChildrenLevelDepth)
);
}
// Add custom exclusion strategies
foreach ($this->exclusionStrategies as $strategy) {
$context->addExclusionStrategy($strategy);
}
// Include null values if a custom select has not been given
if (!$this->customSelectRequested) {
$context->setSerializeNull(true);
}
if ($this->dispatcher->hasListeners(ApiEvents::API_POST_SERIALIZATION_CONTEXT)) {
$apiSerializationContextEvent = new ApiSerializationContextEvent($context, $this->getCurrentRequest());
$this->dispatcher->dispatch($apiSerializationContextEvent, ApiEvents::API_POST_SERIALIZATION_CONTEXT);
$context = $apiSerializationContextEvent->getContext();
}
$view->setContext($context);
}
/**
* @param array<mixed> $parameters
*
* @return array<string, array<mixed>|int|string|null>|bool|Response
*/
protected function validateBatchPayload(array $parameters)
{
$batchLimit = (int) $this->coreParametersHelper->get('api_batch_max_limit', 200);
if (count($parameters) > $batchLimit) {
return $this->returnError($this->translator->trans('mautic.api.call.batch_exception', ['%limit%' => $batchLimit]));
}
return true;
}
/**
* @param mixed|null $data
* @param array<string, string|int> $headers
*/
protected function view($data = null, ?int $statusCode = null, array $headers = []): View
{
if ($data instanceof Paginator) {
// Get iterator out of Paginator class so that the entities are properly serialized by the serializer
$data = iterator_to_array($data->getIterator(), true);
}
$headers['Mautic-Version'] = $this->appVersion->getVersion();
return parent::view($data, $statusCode, $headers);
}
protected function getTotalCountTtl(): ?int
{
return null;
}
}
|