Пример #1
0
 /**
  * @param OrmResultBefore $event
  */
 public function onResultBefore(OrmResultBefore $event)
 {
     $config = $event->getDatagrid()->getConfig();
     if (!$config->offsetGetByPath(Builder::DATASOURCE_SKIP_ACL_CHECK, false)) {
         $this->aclHelper->apply($event->getQuery());
     }
 }
Пример #2
0
 /**
  * @dataProvider dataProvider
  */
 public function testApply(QueryBuilder $queryBuilder, $conditions, $resultHandler, $walkerResult, $exception)
 {
     $eventDispatcher = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface');
     $this->conditionBuilder = $this->getMockBuilder('Oro\\Bundle\\SecurityBundle\\ORM\\Walker\\OwnershipConditionDataBuilder')->disableOriginalConstructor()->getMock();
     $this->conditionBuilder->expects($this->any())->method('getAclConditionData')->will($this->returnCallback(function ($entityName, $permission) use($conditions) {
         if (isset($conditions[$entityName])) {
             return $conditions[$entityName];
         }
         return null;
     }));
     $conditionalFactorBuilder = new AclConditionalFactorBuilder();
     $this->helper = new AclHelper($this->conditionBuilder, $eventDispatcher, $conditionalFactorBuilder);
     $query = $this->helper->apply($queryBuilder);
     $this->{$resultHandler}($query->getHints());
     $parserResult = $this->getMockBuilder('Doctrine\\ORM\\Query\\ParserResult')->disableOriginalConstructor()->getMock();
     $this->assertEquals($query->getDQL(), $queryBuilder->getDQL());
     $this->walker = new AclWalker($query, $parserResult, []);
     $resultAst = $this->walker->walkSelectStatement($query->getAST());
     $this->{$walkerResult}($resultAst);
     if ($exception) {
         list($class, $message) = $exception;
         $this->setExpectedException($class, $message);
     }
     $this->assertNotEmpty($query->getSQL());
 }
 /**
  * @param OrmResultBefore $event
  */
 public function onResultBefore(OrmResultBefore $event)
 {
     $config = $event->getDatagrid()->getConfig();
     if (!$config->isDatasourceSkipAclApply()) {
         $this->aclHelper->apply($event->getQuery());
     }
 }
Пример #4
0
 /**
  * @param ConfigureMenuEvent $event
  */
 public function onNavigationConfigure(ConfigureMenuEvent $event)
 {
     /** @var ItemInterface $reportsMenuItem */
     $reportsMenuItem = $event->getMenu()->getChild('reports_tab');
     if ($reportsMenuItem && $this->securityFacade->hasLoggedUser()) {
         $qb = $this->em->getRepository('OroReportBundle:Report')->createQueryBuilder('report')->orderBy('report.name', 'ASC');
         $reports = $this->aclHelper->apply($qb)->execute();
         if (!empty($reports)) {
             $this->addDivider($reportsMenuItem);
             $reportMenuData = [];
             foreach ($reports as $report) {
                 $config = $this->entityConfigProvider->getConfig($report->getEntity());
                 if ($this->checkAvailability($config)) {
                     $entityLabel = $config->get('plural_label');
                     if (!isset($reportMenuData[$entityLabel])) {
                         $reportMenuData[$entityLabel] = [];
                     }
                     $reportMenuData[$entityLabel][$report->getId()] = $report->getName();
                 }
             }
             ksort($reportMenuData);
             $this->buildReportMenu($reportsMenuItem, $reportMenuData);
         }
     }
 }
Пример #5
0
 /**
  * Calculates count
  *
  * @return int
  */
 public function computeNbResult()
 {
     $qb = clone $this->getQueryBuilder();
     $query = $qb->setFirstResult(null)->setMaxResults(null)->resetDQLPart('orderBy')->getQuery();
     $query = $this->aclHelper->apply($query);
     return QueryCountCalculator::calculateCount($query);
 }
 /**
  * {@inheritdoc}
  */
 public function search($query, $page, $perPage, $searchById = false)
 {
     $query = trim($query);
     $page = (int) $page > 0 ? (int) $page : 1;
     $perPage = (int) $perPage > 0 ? (int) $perPage : 10;
     $firstResult = ($page - 1) * $perPage;
     $perPage += 1;
     $queryBuilder = $this->manager->createQueryBuilder();
     $queryBuilder->from('OroCRMAccountBundle:Account', 'a')->select('a')->leftJoin('OroCRMPartnerBundle:Partner', 'p', 'WITH', 'a = p.account')->where('p.id IS NULL')->setFirstResult($firstResult)->setMaxResults($perPage)->orderBy('a.name');
     if ($query) {
         if ($searchById) {
             $queryBuilder->andWhere('a.id = :id');
             $queryBuilder->setParameters(array('id' => $query));
         } else {
             $queryBuilder->addSelect('LOCATE(:query, a.name) as HIDDEN entry_position');
             $queryBuilder->andWhere('a.name like :search_expression');
             $queryBuilder->orderBy('entry_position');
             $queryBuilder->addOrderBy('a.name');
             $queryBuilder->setParameters(array('query' => $query, 'search_expression' => "%{$query}%"));
         }
     }
     $items = $this->aclHelper->apply($queryBuilder)->execute();
     $hasMore = count($items) == $perPage;
     if ($hasMore) {
         $items = array_slice($items, 0, $perPage - 1);
     }
     return array('results' => $this->convertItems($items), 'more' => $hasMore);
 }
Пример #7
0
 /**
  * Add ACL check to API get list query criteria
  *
  * @param GetListBefore $event
  */
 public function onGetListBefore(GetListBefore $event)
 {
     $acl = $this->securityFacade->getRequestAcl($this->request, true);
     if ($acl && $event->getClassName() === $acl->getClass()) {
         $event->setCriteria($this->aclHelper->applyAclToCriteria($event->getClassName(), $event->getCriteria(), $acl->getPermission()));
     }
 }
Пример #8
0
 /**
  * @param  AclHelper $aclHelper
  * @param $dateStart
  * @param $dateEnd
  * @return array
  */
 protected function getOpportunitiesDataByStatus(AclHelper $aclHelper, $dateStart = null, $dateEnd = null)
 {
     // select statuses
     $qb = $this->getEntityManager()->createQueryBuilder();
     $qb->select('status.name, status.label')->from('OroCRMSalesBundle:OpportunityStatus', 'status')->orderBy('status.name', 'ASC');
     $resultData = array();
     foreach ($qb->getQuery()->getArrayResult() as $status) {
         $name = $status['name'];
         $label = $status['label'];
         $resultData[$name] = array('name' => $name, 'label' => $label, 'budget' => 0);
     }
     // select opportunity data
     $qb = $this->createQueryBuilder('opportunity');
     $qb->select('IDENTITY(opportunity.status) as name, SUM(opportunity.budgetAmount) as budget')->groupBy('opportunity.status');
     if ($dateStart && $dateEnd) {
         $qb->where($qb->expr()->between('opportunity.createdAt', ':dateFrom', ':dateTo'))->setParameter('dateFrom', $dateStart)->setParameter('dateTo', $dateEnd);
     }
     $groupedData = $aclHelper->apply($qb)->getArrayResult();
     foreach ($groupedData as $statusData) {
         $status = $statusData['name'];
         $budget = (double) $statusData['budget'];
         if ($budget) {
             $resultData[$status]['budget'] = $budget;
         }
     }
     return $resultData;
 }
Пример #9
0
 /**
  * @param string $entityClass
  * @param int    $entityId
  * @param string $sorting
  * @return Note[]
  */
 public function getList($entityClass, $entityId, $sorting)
 {
     /** @var NoteRepository $repo */
     $repo = $this->em->getRepository('OroNoteBundle:Note');
     $qb = $repo->getAssociatedNotesQueryBuilder($entityClass, $entityId)->orderBy('note.createdAt', $sorting);
     $query = $this->aclHelper->apply($qb, 'VIEW', false);
     return $query->getResult();
 }
Пример #10
0
 /**
  * @param MassActionHandlerArgs $args
  *
  * @return MassDeleteLimitResult
  */
 public function getLimitResult(MassActionHandlerArgs $args)
 {
     $query = $args->getResults()->getSource();
     $resultsForSelected = new DeletionIterableResult($query);
     $deletableQuery = $this->cloneQuery($query);
     $accessLimitedQuery = $this->aclHelper->apply($deletableQuery, 'DELETE');
     $resultsForDelete = new DeletionIterableResult($accessLimitedQuery);
     return new MassDeleteLimitResult($resultsForSelected->count(), $resultsForDelete->count());
 }
Пример #11
0
 /**
  * @param AclHelper $aclHelper
  * @param int       $recordsCount
  * @param array     $dateRange
  * @return array
  */
 public function getCampaignsByCloseRevenue(AclHelper $aclHelper, $recordsCount, $dateRange = null)
 {
     $qb = $this->getEntityManager()->createQueryBuilder();
     $qb->select('campaign.name as label', 'SUM(CASE WHEN (opp.status=\'won\') THEN opp.closeRevenue ELSE 0 END) as closeRevenue')->from('OroCRMCampaignBundle:Campaign', 'campaign')->join('OroCRMSalesBundle:Lead', 'lead', 'WITH', 'lead.campaign = campaign')->join('lead.opportunities', 'opp')->orderBy('closeRevenue', 'DESC')->groupBy('campaign.name')->setMaxResults($recordsCount);
     if ($dateRange) {
         $qb->where($qb->expr()->between('opp.createdAt', ':dateFrom', ':dateTo'))->setParameter('dateFrom', $dateRange['start'])->setParameter('dateTo', $dateRange['end']);
     }
     return $aclHelper->apply($qb)->getArrayResult();
 }
Пример #12
0
 /**
  * {@inheritdoc}
  */
 public function process(ContextInterface $context)
 {
     /** @var Context $context */
     if ($context->hasQuery()) {
         // a query is already built
         return;
     }
     $this->aclHelper->applyAclToCriteria($context->getClassName(), $context->getCriteria(), $this->permission);
 }
Пример #13
0
 /**
  * Returns top $limit opportunities grouped by lead source
  *
  * @param  AclHelper $aclHelper
  * @param  int       $limit
  * @param  array     $dateRange
  * @return array     [itemCount, label]
  */
 public function getOpportunitiesByLeadSource(AclHelper $aclHelper, $limit = 10, $dateRange = null)
 {
     $qb = $this->createQueryBuilder('l')->select('s.id as source, count(o.id) as itemCount')->leftJoin('l.opportunities', 'o')->leftJoin('l.source', 's')->groupBy('source');
     if ($dateRange) {
         $qb->andWhere($qb->expr()->between('o.createdAt', ':dateStart', ':dateEnd'))->setParameter('dateStart', $dateRange['start'])->setParameter('dateEnd', $dateRange['end']);
     }
     $rows = $aclHelper->apply($qb)->getArrayResult();
     return $this->processOpportunitiesByLeadSource($rows, $limit);
 }
 /**
  * @return ResultRecordInterface[]
  */
 public function getResults()
 {
     $query = $this->aclHelper->apply($this->qb->getQuery());
     $results = $query->execute();
     $rows = [];
     foreach ($results as $result) {
         $rows[] = new ResultRecord($result);
     }
     return $rows;
 }
Пример #15
0
 /**
  * {@inheritdoc}
  */
 public function setDefaultOptions(OptionsResolverInterface $resolver)
 {
     $choices = function (Options $options) {
         if (empty($options['entity_class'])) {
             return [];
         }
         return $this->aclHelper->apply($this->doctrine->getRepository('OroTagBundle:Tag')->createQueryBuilder('t')->join('t.tagging', 'tagging')->where('tagging.entityName = :entity')->setParameter('entity', $options['entity_class']))->getResult();
     };
     $resolver->setDefaults(['class' => 'OroTagBundle:Tag', 'property' => 'name', 'entity_class' => null, 'choices' => $choices]);
 }
Пример #16
0
 /**
  * @param DateTime $from
  * @param DateTime $to
  *
  * @return int
  */
 public function getVisitedCount(DateTime $from, DateTime $to)
 {
     $qb = $this->getTrackingVisitRepository()->createQueryBuilder('t');
     try {
         $qb->select('COUNT(DISTINCT t.userIdentifier)')->join('t.trackingWebsite', 'tw')->join('tw.channel', 'c')->andWhere('c.channelType = :channel')->andWhere($qb->expr()->eq('c.status', ':status'))->andWhere($qb->expr()->between('t.firstActionTime', ':from', ':to'))->setParameters(['channel' => ChannelType::TYPE, 'from' => $from, 'to' => $to, 'status' => Channel::STATUS_ACTIVE]);
         return (int) $this->aclHelper->apply($qb)->getSingleScalarResult();
     } catch (NoResultException $ex) {
         return 0;
     }
 }
Пример #17
0
 /**
  * @return array
  */
 public function getList()
 {
     $response = [];
     $qb = $this->registry->getManager()->getRepository('OroUserBundle:User')->createQueryBuilder('u');
     $users = $this->aclHelper->apply($qb)->getResult();
     /** @var User $user */
     foreach ($users as $user) {
         $response[] = ['id' => $user->getId(), 'name' => $user->getFullName()];
     }
     return $response;
 }
Пример #18
0
 /**
  * @param array  $dateRange
  * @param string $entity
  * @param string $field
  *
  * @return \DateTime[]
  */
 public function getPeriod($dateRange, $entity, $field)
 {
     $start = $dateRange['start'];
     $end = $dateRange['end'];
     if ($dateRange['type'] === AbstractDateFilterType::TYPE_LESS_THAN) {
         $qb = $this->doctrine->getRepository($entity)->createQueryBuilder('e')->select(sprintf('MIN(e.%s) as val', $field));
         $start = $this->aclHelper->apply($qb)->getSingleScalarResult();
         $start = new \DateTime($start, new \DateTimeZone('UTC'));
     }
     return [$start, $end];
 }
Пример #19
0
 /**
  * get Average Order Amount by given period
  *
  * @param \DateTime $start
  * @param \DateTime $end
  * @param AclHelper $aclHelper
  * @return int
  */
 public function getAverageOrderValue(\DateTime $start, \DateTime $end, AclHelper $aclHelper)
 {
     $select = 'SUM(
          CASE WHEN o.grandTotal IS NOT NULL THEN o.grandTotal ELSE 0 END
          ) as revenue,
          count(o.id) as ordersCount';
     $qb = $this->createQueryBuilder('o');
     $qb->select($select)->andWhere($qb->expr()->between('o.createdAt', ':dateStart', ':dateEnd'))->setParameter('dateStart', $start)->setParameter('dateEnd', $end);
     $value = $aclHelper->apply($qb)->getOneOrNullResult();
     return $value['revenue'] ? $value['revenue'] / $value['ordersCount'] : 0;
 }
 /**
  * @param ActivityListProviderInterface $provider
  * @param $mapFields
  *
  * @return Criteria
  */
 protected function getCriteriaByProvider(ActivityListProviderInterface $provider, $mapFields)
 {
     $activityClass = $provider->getActivityClass();
     $aclClass = $provider->getAclClass();
     $criteria = new Criteria();
     $appliedCriteria = $this->aclHelper->applyAclToCriteria($aclClass, $criteria, 'VIEW', $mapFields);
     $isGranted = $this->securityContextLink->getService()->isGranted('VIEW', 'entity:' . $aclClass);
     if ($isGranted) {
         $appliedCriteria->andWhere(Criteria::expr()->eq('relatedActivityClass', $activityClass));
     }
     return $appliedCriteria;
 }
Пример #21
0
 /**
  * Returns a list of organization ids for which, current user has permission to update them.
  *
  * @return array
  */
 protected function getAuthorisedOrganizationIds()
 {
     /** @var EntityManager $manager */
     $manager = $this->doctrine->getManagerForClass('OroOrganizationBundle:Organization');
     $qb = $manager->createQueryBuilder();
     $qb->select('o.id')->from('OroOrganizationBundle:Organization', 'o');
     $query = $qb->getQuery();
     $query = $this->aclHelper->apply($query, 'EDIT');
     $result = $query->getArrayResult();
     $result = array_map('current', $result);
     return $result;
 }
Пример #22
0
 /**
  * Calculates count
  *
  * @return int
  */
 public function computeNbResult()
 {
     $countQb = $this->countQueryBuilderOptimizer->getCountQueryBuilder($this->getQueryBuilder());
     $query = $countQb->getQuery();
     if (!$this->skipAclCheck) {
         $query = $this->aclHelper->apply($query);
     }
     $useWalker = null;
     if ($this->skipCountWalker !== null) {
         $useWalker = !$this->skipCountWalker;
     }
     return QueryCountCalculator::calculateCount($query, $useWalker);
 }
Пример #23
0
 /**
  * {@inheritdoc}
  */
 public function getCalendarEvents($organizationId, $userId, $calendarId, $start, $end, $connections, $extraFields = [])
 {
     if (!$this->myTasksEnabled) {
         return [];
     }
     if ($this->isCalendarVisible($connections, self::MY_TASKS_CALENDAR_ID)) {
         /** @var TaskRepository $repo */
         $repo = $this->doctrineHelper->getEntityRepository('OroCRMTaskBundle:Task');
         $qb = $repo->getTaskListByTimeIntervalQueryBuilder($userId, $start, $end, $extraFields);
         $query = $this->aclHelper->apply($qb);
         return $this->taskCalendarNormalizer->getTasks(self::MY_TASKS_CALENDAR_ID, $query);
     }
     return [];
 }
Пример #24
0
 /**
  * @dataProvider getLimitQueryDataProvider
  *
  * @param MassDeleteLimitResult $limitResult
  * @param bool                  $accessRestriction
  * @param bool                  $maxLimitRestriction
  *
  * @internal     param $MassDeleteLimitResult $
  */
 public function testLimitQuery(MassDeleteLimitResult $limitResult, $accessRestriction = false, $maxLimitRestriction = false)
 {
     /** @var QueryBuilder|\PHPUnit_Framework_MockObject_MockObject $queryBuilder */
     $queryBuilder = $this->getMockBuilder('Doctrine\\ORM\\QueryBuilder')->disableOriginalConstructor()->getMock();
     /** @var MassActionHandlerArgs|\PHPUnit_Framework_MockObject_MockObject $args */
     $args = $this->getMockBuilder('Oro\\Bundle\\DataGridBundle\\Extension\\MassAction\\MassActionHandlerArgs')->disableOriginalConstructor()->getMock();
     $args->expects($this->once())->method('getResults')->willReturn(new DeletionIterableResult($queryBuilder));
     if ($accessRestriction) {
         $this->helper->expects($this->once())->method('apply')->with($queryBuilder, 'DELETE');
     }
     if ($maxLimitRestriction) {
         $queryBuilder->expects($this->once())->method('setMaxResults')->with($limitResult->getMaxLimit());
     }
     $this->limiter->limitQuery($limitResult, $args);
 }
Пример #25
0
 /**
  * @param QueryBuilder $qb
  * @param EmailRecipientsProviderArgs $args
  *
  * @return array
  */
 protected function getRestrictedResult(QueryBuilder $qb, EmailRecipientsProviderArgs $args)
 {
     if ($args->getOrganization()) {
         $qb->andWhere('o.id = :organization')->setParameter('organization', $args->getOrganization());
     }
     return $this->aclHelper->apply($qb)->getResult();
 }
Пример #26
0
 /**
  * @param AclHelper $aclHelper
  * @param int $customerId
  * @return array
  */
 public function getChildrenIds(AclHelper $aclHelper, $customerId)
 {
     $qb = $this->createQueryBuilder('customer');
     $qb->select('customer.id as customer_id')->where($qb->expr()->eq('IDENTITY(customer.parent)', ':parent'))->setParameter('parent', $customerId);
     $result = $aclHelper->apply($qb)->getArrayResult();
     $result = array_map(function ($item) {
         return $item['customer_id'];
     }, $result);
     $children = $result;
     if ($result) {
         foreach ($result as $childId) {
             $children = array_merge($children, $this->getChildrenIds($aclHelper, $childId));
         }
     }
     return $children;
 }
 /**
  * @param Organization $currentOrganization
  *
  * @return array
  */
 public function getList()
 {
     $businessUnitRepository = $this->getBusinessUnitRepo();
     $response = [];
     $qb = $businessUnitRepository->getQueryBuilder();
     $businessUnits = $this->aclHelper->apply($qb)->getResult();
     /** @var BusinessUnit $businessUnit */
     foreach ($businessUnits as $businessUnit) {
         if ($businessUnit->getOwner()) {
             $name = $businessUnit->getName();
         } else {
             $name = $this->getBusinessUnitName($businessUnit);
         }
         $response[] = ['id' => $businessUnit->getId(), 'name' => $name, 'owner_id' => $businessUnit->getOwner() ? $businessUnit->getOwner()->getId() : null];
     }
     return $response;
 }
Пример #28
0
 /**
  * Get ordered list of case comments
  *
  * @param CaseEntity $case
  * @param string $order
  * @return CaseComment[]
  */
 public function getCaseComments(CaseEntity $case, $order = 'DESC')
 {
     $order = strtoupper($order) == 'ASC' ? $order : 'DESC';
     $repository = $this->entityManager->getRepository('OroCRMCaseBundle:CaseComment');
     $queryBuilder = $repository->createQueryBuilder('comment')->where('comment.case = :case')->orderBy('comment.createdAt', $order)->setParameter('case', $case);
     $query = $this->aclHelper->apply($queryBuilder);
     return $query->getResult();
 }
Пример #29
0
 /**
  * Returns data grouped by created_at, data_channel_id
  *
  * @param AclHelper  $aclHelper
  * @param DateHelper $dateHelper
  * @param \DateTime  $dateFrom
  * @param \DateTime  $dateTo
  * @param array      $ids Filter by channel ids
  *
  * @return array
  */
 public function getGroupedByChannelArray(AclHelper $aclHelper, DateHelper $dateHelper, \DateTime $dateFrom, \DateTime $dateTo = null, $ids = [])
 {
     $qb = $this->createQueryBuilder('c');
     $qb->select('COUNT(c) as cnt', 'IDENTITY(c.dataChannel) as channelId');
     $dateHelper->addDatePartsSelect($dateFrom, $dateTo, $qb, 'c.createdAt');
     if ($dateTo) {
         $qb->andWhere($qb->expr()->between('c.createdAt', ':dateFrom', ':dateTo'))->setParameter('dateTo', $dateTo);
     } else {
         $qb->andWhere('c.createdAt > :dateFrom');
     }
     $qb->setParameter('dateFrom', $dateFrom);
     $qb->addGroupBy('c.dataChannel');
     if ($ids) {
         $qb->andWhere($qb->expr()->in('c.dataChannel', ':channelIds'))->setParameter('channelIds', $ids);
     }
     return $aclHelper->apply($qb)->getArrayResult();
 }
Пример #30
0
 /**
  * @param array $entityIds
  * @return array
  */
 protected function getEntitiesByIds(array $entityIds)
 {
     /** @var QueryBuilder $queryBuilder */
     $queryBuilder = $this->entityRepository->createQueryBuilder('e');
     $queryBuilder->where($queryBuilder->expr()->in('e.' . $this->idFieldName, $entityIds));
     $query = $this->aclHelper->apply($queryBuilder, 'VIEW');
     return $query->getResult();
 }