vendor/pimcore/portal-engine/src/EventSubscriber/StatisticsSubscriber.php line 185

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under following license:
  6.  * - Pimcore Commercial License (PCL)
  7.  *
  8.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  9.  *  @license    http://www.pimcore.org/license     PCL
  10.  */
  11. namespace Pimcore\Bundle\PortalEngineBundle\EventSubscriber;
  12. use Carbon\Carbon;
  13. use ONGR\ElasticsearchDSL\Query\Compound\BoolQuery;
  14. use ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery;
  15. use ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery;
  16. use ONGR\ElasticsearchDSL\Search;
  17. use Pimcore\Bundle\PortalEngineBundle\Enum\ElasticSearchFields;
  18. use Pimcore\Bundle\PortalEngineBundle\Enum\Statistics;
  19. use Pimcore\Bundle\PortalEngineBundle\Model\Configuration\DataPool\AssetConfig;
  20. use Pimcore\Bundle\PortalEngineBundle\Model\Configuration\DataPool\DataObjectConfig;
  21. use Pimcore\Bundle\PortalEngineBundle\Service\DataPool\DataPoolConfigService;
  22. use Pimcore\Bundle\PortalEngineBundle\Service\Element\NameExtractorService;
  23. use Pimcore\Bundle\PortalEngineBundle\Service\Element\UrlExtractorService;
  24. use Pimcore\Bundle\PortalEngineBundle\Service\PortalConfig\PortalConfigService;
  25. use Pimcore\Bundle\PortalEngineBundle\Service\SearchIndex\Asset;
  26. use Pimcore\Bundle\PortalEngineBundle\Service\SearchIndex\DataObject;
  27. use Pimcore\Bundle\PortalEngineBundle\Service\SearchIndex\ElasticSearchConfigService;
  28. use Pimcore\Bundle\PortalEngineBundle\Service\SearchIndex\Search\PreConditionService;
  29. use Pimcore\Bundle\PortalEngineBundle\Service\Security\PermissionService;
  30. use Pimcore\Bundle\PortalEngineBundle\Service\Security\SecurityService;
  31. use Pimcore\Bundle\StatisticsExplorerBundle\Events\DataFilterModificationEvent;
  32. use Pimcore\Bundle\StatisticsExplorerBundle\Events\DataResultEvent;
  33. use Pimcore\Bundle\StatisticsExplorerBundle\Events\StatisticsServiceInitEvent;
  34. use Pimcore\Bundle\StatisticsExplorerBundle\Events\TableRenderEvent;
  35. use Pimcore\Bundle\StatisticsExplorerBundle\Model\StatisticsResult;
  36. use Pimcore\Bundle\StatisticsExplorerBundle\StatisticsStorageAdapter\ElasticsearchAdapter;
  37. use Pimcore\Bundle\StatisticsExplorerBundle\StatisticsStorageAdapter\StatisticsStorageAdapterInterface;
  38. use Pimcore\Bundle\StatisticsExplorerBundle\StatisticsStorageAdapter\Worker\ElasticsearchListWorker;
  39. use Pimcore\Bundle\StatisticsExplorerBundle\StatisticsStorageAdapter\Worker\ElasticsearchStatisticWorker;
  40. use Pimcore\Bundle\StatisticsExplorerBundle\Tools\ElasticsearchClientFactory;
  41. use Pimcore\Model\DataObject\ClassDefinition;
  42. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  43. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  44. class StatisticsSubscriber implements EventSubscriberInterface
  45. {
  46.     /**
  47.      * @var DataObject\Search\WorkspaceService
  48.      */
  49.     protected $dataObjectWorkspaceService;
  50.     /**
  51.      * @var Asset\Search\WorkspaceService
  52.      */
  53.     protected $assetWorkspaceService;
  54.     /**
  55.      * @var DataPoolConfigService $dataPoolConfigService
  56.      */
  57.     protected $dataPoolConfigService;
  58.     /**
  59.      * @var PermissionService
  60.      */
  61.     protected $permissionService;
  62.     /**
  63.      * @var SecurityService
  64.      */
  65.     protected $securityService;
  66.     /**
  67.      * @var PreConditionService
  68.      */
  69.     protected $preConditionService;
  70.     /**
  71.      * @var PortalConfigService
  72.      */
  73.     protected $portalConfigService;
  74.     /**
  75.      * @var ElasticsearchClientFactory
  76.      */
  77.     protected $elasticsearchClientFactory;
  78.     /**
  79.      * @var ElasticsearchStatisticWorker
  80.      */
  81.     protected $statisticWorker;
  82.     /**
  83.      * @var ElasticsearchListWorker
  84.      */
  85.     protected $listWorker;
  86.     /**
  87.      * @var EventDispatcherInterface
  88.      */
  89.     protected $eventDispatcher;
  90.     /**
  91.      * @var ElasticSearchConfigService
  92.      */
  93.     protected $elasticSearchConfigService;
  94.     /**
  95.      * @var NameExtractorService
  96.      */
  97.     protected $nameExtractorService;
  98.     /**
  99.      * @var UrlExtractorService
  100.      */
  101.     protected $urlExtractorService;
  102.     /**
  103.      * StatisticsSubscriber constructor.
  104.      *
  105.      * @param DataObject\Search\WorkspaceService $dataObjectWorkspaceService
  106.      * @param Asset\Search\WorkspaceService $assetWorkspaceService
  107.      * @param DataPoolConfigService $dataPoolConfigService
  108.      * @param PermissionService $permissionService
  109.      * @param SecurityService $securityService
  110.      * @param PreConditionService $preConditionService
  111.      * @param PortalConfigService $portalConfigService
  112.      * @param ElasticsearchClientFactory $elasticsearchClientFactory
  113.      * @param ElasticsearchStatisticWorker $statisticWorker
  114.      * @param ElasticsearchListWorker $listWorker
  115.      * @param EventDispatcherInterface $eventDispatcher
  116.      * @param ElasticSearchConfigService $elasticSearchConfigService
  117.      * @param NameExtractorService $nameExtractorService
  118.      * @param UrlExtractorService $urlExtractorService
  119.      */
  120.     public function __construct(
  121.         DataObject\Search\WorkspaceService $dataObjectWorkspaceService,
  122.         Asset\Search\WorkspaceService $assetWorkspaceService,
  123.         DataPoolConfigService $dataPoolConfigService,
  124.         PermissionService $permissionService,
  125.         SecurityService $securityService,
  126.         PreConditionService $preConditionService,
  127.         PortalConfigService $portalConfigService,
  128.         ElasticsearchClientFactory $elasticsearchClientFactory,
  129.         ElasticsearchStatisticWorker $statisticWorker,
  130.         ElasticsearchListWorker $listWorker,
  131.         EventDispatcherInterface $eventDispatcher,
  132.         ElasticSearchConfigService $elasticSearchConfigService,
  133.         NameExtractorService $nameExtractorService,
  134.         UrlExtractorService $urlExtractorService
  135.     ) {
  136.         $this->dataObjectWorkspaceService $dataObjectWorkspaceService;
  137.         $this->assetWorkspaceService $assetWorkspaceService;
  138.         $this->dataPoolConfigService $dataPoolConfigService;
  139.         $this->permissionService $permissionService;
  140.         $this->securityService $securityService;
  141.         $this->preConditionService $preConditionService;
  142.         $this->portalConfigService $portalConfigService;
  143.         $this->elasticsearchClientFactory $elasticsearchClientFactory;
  144.         $this->statisticWorker $statisticWorker;
  145.         $this->listWorker $listWorker;
  146.         $this->eventDispatcher $eventDispatcher;
  147.         $this->elasticSearchConfigService $elasticSearchConfigService;
  148.         $this->nameExtractorService $nameExtractorService;
  149.         $this->urlExtractorService $urlExtractorService;
  150.     }
  151.     public static function getSubscribedEvents()
  152.     {
  153.         return [
  154.             DataFilterModificationEvent::class => 'modifyStatisticsFilter',
  155.             DataResultEvent::class => 'modifyDataResult',
  156.             StatisticsServiceInitEvent::class => 'addDataObjectClassSources',
  157.             TableRenderEvent::class => 'renderAssetListing'
  158.         ];
  159.     }
  160.     /**
  161.      * @param DataFilterModificationEvent $event
  162.      *
  163.      * @throws \Exception
  164.      */
  165.     public function modifyStatisticsFilter(DataFilterModificationEvent $event)
  166.     {
  167.         if ($event->getConfiguration() && in_array($event->getConfiguration()->getName(), Statistics::ASSET_STATISTICS)) {
  168.             $this->applyAssetDataPoolFilter($event);
  169.         } elseif ($event->getConfiguration() && in_array($event->getConfiguration()->getName(), Statistics::DATA_OBJECT_STATISTICS)) {
  170.             $this->applyDataObjectDataPoolFilter($event);
  171.         } elseif ($event->getConfiguration() && $event->getConfiguration()->getName() === Statistics::ALL_LOGINS_LAST_SIX_MONTHS) {
  172.             $this->applyLoginsFilter($event);
  173.         }
  174.         if ($event->getConfiguration() && in_array($event->getConfiguration()->getName(), Statistics::ADD_6_MONTHS_CONDITION)) {
  175.             $this->addLast6MonthsFilter($event);
  176.         }
  177.         if ($event->getConfiguration() && in_array($event->getConfiguration()->getName(), Statistics::ADD_USER_CONDITION)) {
  178.             $this->addUserFilter($event);
  179.         }
  180.     }
  181.     public function modifyDataResult(DataResultEvent $event)
  182.     {
  183.         if ($event->getConfiguration() && $event->getConfiguration()->getName() === Statistics::ASSET_STORAGE_BY_TYPES) {
  184.             $statisticResult $event->getStatisticsResult();
  185.             $data $statisticResult->getData();
  186.             foreach ($data as $key => $row) {
  187.                 $data[$key]['value'] = ceil($row['value'] / 1000 1000);
  188.                 $data[$key]['label'] = str_replace(' system_fields.fileSize sum'''$row['label']);
  189.             }
  190.             $statisticResult = new StatisticsResult(
  191.                 $data,
  192.                 $statisticResult->getColumnHeaders(),
  193.                 $statisticResult->getRowHeaders()
  194.             );
  195.             $event->setStatisticsResult($statisticResult);
  196.         }
  197.         if ($event->getConfiguration() && in_array($event->getConfiguration()->getName(), Statistics::FORMAT_TIMESTAMP_STATISTICS)) {
  198.             $statisticResult $event->getStatisticsResult();
  199.             $data $statisticResult->getData();
  200.             foreach ($data as $key => $row) {
  201.                 $data[$key]['timestamp'] = date('Y-m-d H:i:s'strtotime($row['timestamp']));
  202.             }
  203.             $statisticResult = new StatisticsResult(
  204.                 $data,
  205.                 $statisticResult->getColumnHeaders(),
  206.                 $statisticResult->getRowHeaders()
  207.             );
  208.             $event->setStatisticsResult($statisticResult);
  209.         }
  210.     }
  211.     /**
  212.      * @param DataFilterModificationEvent $event
  213.      *
  214.      * @throws \Exception
  215.      */
  216.     protected function applyAssetDataPoolFilter(DataFilterModificationEvent $event)
  217.     {
  218.         $boolQuery = new BoolQuery();
  219.         foreach ($this->dataPoolConfigService->getDataPoolConfigsFromSite() as $dataPoolConfig) {
  220.             if ($dataPoolConfig instanceof AssetConfig) {
  221.                 $this->dataPoolConfigService->setCurrentDataPoolConfig($dataPoolConfig);
  222.                 $mustQuery = new BoolQuery();
  223.                 $mustQuery->add($this->assetWorkspaceService->getElasticSearchWorkspaceQuery(), BoolQuery::MUST);
  224.                 $search = new Search();
  225.                 $this->preConditionService->applyElasticSearchPreConditions($search);
  226.                 if ($search->getQueries()) {
  227.                     $mustQuery->add($search->getQueries(), BoolQuery::MUST);
  228.                 }
  229.                 $boolQuery->add($mustQueryBoolQuery::SHOULD);
  230.             }
  231.         }
  232.         $excludeFolderQuery = new TermQuery(ElasticSearchFields::SYSTEM_FIELDS '.' ElasticSearchFields::SYSTEM_FIELDS_TYPE'folder');
  233.         $boolQuery->add($excludeFolderQueryBoolQuery::MUST_NOT);
  234.         $event->setFilter($boolQuery->toArray());
  235.     }
  236.     /**
  237.      * @param DataFilterModificationEvent $event
  238.      *
  239.      * @throws \Exception
  240.      */
  241.     protected function applyDataObjectDataPoolFilter(DataFilterModificationEvent $event)
  242.     {
  243.         $boolQuery = new BoolQuery();
  244.         foreach ($this->dataPoolConfigService->getDataPoolConfigsFromSite() as $dataPoolConfig) {
  245.             if ($dataPoolConfig instanceof DataObjectConfig) {
  246.                 $this->dataPoolConfigService->setCurrentDataPoolConfig($dataPoolConfig);
  247.                 $mustQuery = new BoolQuery();
  248.                 $mustQuery->add($this->dataObjectWorkspaceService->getElasticSearchWorkspaceQuery(), BoolQuery::MUST);
  249.                 $classDefinition ClassDefinition::getById($dataPoolConfig->getDataObjectClass());
  250.                 $className $classDefinition $classDefinition->getName() : '-1';
  251.                 $classNameQuery = new TermQuery(ElasticSearchFields::SYSTEM_FIELDS '.' ElasticSearchFields::SYSTEM_FIELDS_CLASS_NAME '.keyword'$className);
  252.                 $mustQuery->add($classNameQueryBoolQuery::MUST);
  253.                 $search = new Search();
  254.                 $this->preConditionService->applyElasticSearchPreConditions($search);
  255.                 if ($search->getQueries()) {
  256.                     $mustQuery->add($search->getQueries(), BoolQuery::MUST);
  257.                 }
  258.                 $boolQuery->add($mustQueryBoolQuery::SHOULD);
  259.             }
  260.         }
  261.         $event->setFilter($boolQuery->toArray());
  262.     }
  263.     /**
  264.      * @param DataFilterModificationEvent $event
  265.      *
  266.      * @throws \Exception
  267.      */
  268.     protected function applyLoginsFilter(DataFilterModificationEvent $event)
  269.     {
  270.         $filter = new TermQuery('portalId'$this->portalConfigService->getCurrentPortalConfig()->getPortalId());
  271.         $event->setFilter($filter->toArray());
  272.     }
  273.     protected function addLast6MonthsFilter(DataFilterModificationEvent $event)
  274.     {
  275.         $timestampQuery = new RangeQuery(
  276.             'timestamp', [
  277.                 RangeQuery::GTE => Carbon::createFromTimestamp(strtotime(date('Y-m-1')))->subMonths(6)->format(
  278.                     'Y-m-d\TH:i:sO'
  279.                 ),
  280.             ]
  281.         );
  282.         $event->setFilter([
  283.            'bool' => [
  284.                'must' => [
  285.                    $timestampQuery->toArray(),
  286.                    $event->getFilter()
  287.                ]
  288.            ]
  289.         ]);
  290.     }
  291.     protected function addUserFilter(DataFilterModificationEvent $event)
  292.     {
  293.         $timestampQuery = new TermQuery(
  294.             'userId'$this->securityService->getPortalUser()->getId()
  295.         );
  296.         $event->setFilter([
  297.            'bool' => [
  298.                'must' => [
  299.                    $timestampQuery->toArray(),
  300.                    $event->getFilter()
  301.                ]
  302.            ]
  303.         ]);
  304.     }
  305.     public function addDataObjectClassSources(StatisticsServiceInitEvent $event)
  306.     {
  307.         $statisticsService $event->getStatisticsService();
  308.         $dataPools $this->dataPoolConfigService->getDataPoolConfigsFromSite();
  309.         $classIds = [];
  310.         foreach ($dataPools as $dataPool) {
  311.             if ($dataPool instanceof DataObjectConfig) {
  312.                 $classIds[] = $dataPool->getDataObjectClass();
  313.             }
  314.         }
  315.         $classes = [];
  316.         foreach (array_unique($classIds) as $classId) {
  317.             $classes[] = ClassDefinition::getById($classId);
  318.         }
  319.         foreach ($classes as $class) {
  320.             $indexName $this->elasticSearchConfigService->getIndexName($class->getName());
  321.             $label 'DataObject `' $class->getName() . '`';
  322.             $adapter = new ElasticsearchAdapter($this->elasticsearchClientFactory$indexName$this->statisticWorker$this->listWorker$this->eventDispatcher$label);
  323.             $statisticsService->addDataSourceAdapter('pimcoreportalengine_' $class->getId(), 'portal'$adapter);
  324.         }
  325.     }
  326.     public function renderAssetListing(TableRenderEvent $event)
  327.     {
  328.         if ($event->getConfiguration() && in_array($event->getConfiguration()->getName(), Statistics::RENDER_AS_ASSET_TABLE)) {
  329.             $params $event->getParameters();
  330.             $newParams = [];
  331.             if ($event->getStatisticsMode() === StatisticsStorageAdapterInterface::STATISTICS_MODE_LIST) {
  332.                 if (($params['columnHeaders']['0']['value'] ?? null) === 'system_fields.id') {
  333.                     $newParams = [
  334.                         'labels' => ['asset' => 'Asset''timestamp' => 'Timestamp'],
  335.                         'data' => []
  336.                     ];
  337.                     foreach ($params['data'] as $dataEntry) {
  338.                         $asset \Pimcore\Model\Asset::getById($dataEntry['system_fields.id']);
  339.                         if (empty($asset)) {
  340.                             $dataEntry['asset_name'] = $dataEntry['path'];
  341.                             $dataEntry['asset_url'] = false;
  342.                         } else {
  343.                             $dataEntry['asset_name'] = $this->nameExtractorService->extractName($asset);
  344.                             $dataEntry['asset_url'] = $this->urlExtractorService->extractUrl($asset);
  345.                         }
  346.                         $newParams['data'][] = $dataEntry;
  347.                     }
  348.                 }
  349.             } else {
  350.                 $newParams = [
  351.                     'labels' => ['asset' => 'Asset''result' => 'Result'],
  352.                     'data' => []
  353.                 ];
  354.                 foreach ($params['rowHeaders'] as $row) {
  355.                     $dataEntry = [];
  356.                     $rowHeaders $row['rowHeaders'];
  357.                     $asset \Pimcore\Model\Asset::getById($rowHeaders[0]['value']);
  358.                     if (empty($asset)) {
  359.                         $dataEntry['asset_name'] = $rowHeaders[1]['value'];
  360.                         $dataEntry['asset_url'] = false;
  361.                     } else {
  362.                         $dataEntry['asset_name'] = $this->nameExtractorService->extractName($asset);
  363.                         $dataEntry['asset_url'] = $this->urlExtractorService->extractUrl($asset);
  364.                     }
  365.                     $dataEntry['result'] = $params['data'][$row['dataKey']]['value'] ?? '-';
  366.                     $newParams['data'][] = $dataEntry;
  367.                 }
  368.             }
  369.             $event->setParameters($newParams);
  370.             $event->setTemplate('@PimcorePortalEngine/statistic_explorer/asset-data-list.html.twig');
  371.         }
  372.     }
  373. }