Exemplo n.º 1
0
 /**
  * @param object $object
  * @param int $depth
  * @param bool $ignoreAcl
  * @param Organization|null $organization
  *
  * @return Recipient[]
  */
 public function getRecipients($object, $depth = 1, $ignoreAcl = false, Organization $organization = null)
 {
     $recipients = [];
     if ($this->isAccessDenyForOrganization($object, $ignoreAcl, $organization)) {
         return $recipients;
     }
     if (!$depth || ($ignoreAcl || !$this->securityFacade->isGranted('VIEW', $object))) {
         if (!$depth || $this->securityFacade->getLoggedUser() !== $object) {
             return $recipients;
         }
     }
     $className = ClassUtils::getClass($object);
     $metadata = $this->getMetadata($className);
     $attributes = $this->initAttributes($className, $metadata);
     foreach ($metadata->associationMappings as $name => $assoc) {
         if (in_array('Oro\\Bundle\\EmailBundle\\Entity\\EmailInterface', class_implements($assoc['targetEntity']), true)) {
             $attributes[] = new EmailAttribute($name, true);
         } else {
             if ($depth > 1) {
                 $assocObject = $this->getPropertyAccessor()->getValue($object, $name);
                 if (!$assocObject instanceof \Traversable && !is_array($assocObject)) {
                     if ($assocObject) {
                         $assocObject = [$assocObject];
                     } else {
                         $assocObject = [];
                     }
                 }
                 foreach ($assocObject as $obj) {
                     $recipients = array_merge($recipients, $this->getRecipients($obj, $depth - 1, false, $organization));
                 }
             }
         }
     }
     return array_merge($recipients, $this->createRecipientsFromEmails($this->createEmailsFromAttributes($attributes, $object), $object, $metadata));
 }
 /**
  * {@inheritDoc}
  * @throws \Doctrine\DBAL\ConnectionException
  */
 protected function onSuccess(AbstractRole $role, array $appendUsers, array $removeUsers)
 {
     // TODO: When task BB-1046 will be done, remove method removeOriginalRoleFromUsers.
     // In method addNewRoleToUsers before addRole add method removeRole($role). Also needs delete flush;
     /** @var AccountUserRole $role */
     if ($role->getId()) {
         /** @var AccountUserRoleRepository $roleRepository */
         $roleRepository = $this->doctrineHelper->getEntityRepository($role);
         $this->appendUsers = $roleRepository->getAssignedUsers($role);
     }
     $this->loggedAccountUser = $this->securityFacade->getLoggedUser();
     /** @var EntityManager $manager */
     $manager = $this->managerRegistry->getManagerForClass(ClassUtils::getClass($this->loggedAccountUser));
     $connection = $manager->getConnection();
     $connection->setTransactionIsolation(Connection::TRANSACTION_REPEATABLE_READ);
     $connection->beginTransaction();
     try {
         $this->removeOriginalRoleFromUsers($role, $manager);
         AclRoleHandler::onSuccess($this->newRole, $appendUsers, $removeUsers);
         $this->addNewRoleToUsers($role, $manager, $appendUsers, $removeUsers);
         $manager->flush();
         $connection->commit();
     } catch (\Exception $e) {
         $connection->rollBack();
         throw $e;
     }
 }
Exemplo n.º 3
0
 /**
  * Returns the context for the given email
  *
  * @param Email $email
  *
  * @return array
  */
 public function getEmailContext(Email $email)
 {
     $criteria = Criteria::create();
     $criteria->andWhere(Criteria::expr()->eq('id', $email->getId()));
     $qb = $this->activityManager->getActivityTargetsQueryBuilder($this->class, $criteria);
     if (null === $qb) {
         return [];
     }
     $result = $qb->getQuery()->getResult();
     if (empty($result)) {
         return $result;
     }
     $currentUser = $this->securityFacade->getLoggedUser();
     $currentUserClass = ClassUtils::getClass($currentUser);
     $currentUserId = $currentUser->getId();
     $result = array_values(array_filter($result, function ($item) use($currentUserClass, $currentUserId) {
         return !($item['entity'] === $currentUserClass && $item['id'] == $currentUserId);
     }));
     foreach ($result as &$item) {
         $route = $this->configManager->getEntityMetadata($item['entity'])->getRoute();
         $item['entityId'] = $email->getId();
         $item['targetId'] = $item['id'];
         $item['targetClassName'] = $this->entityClassNameHelper->getUrlSafeClassName($item['entity']);
         $item['icon'] = $this->configManager->getProvider('entity')->getConfig($item['entity'])->get('icon');
         $item['link'] = $route ? $this->router->generate($route, ['id' => $item['id']]) : null;
         unset($item['id'], $item['entity']);
     }
     return $result;
 }
 /**
  * Sets default data for create integrations form
  *
  * @param FormEvent $event
  */
 public function postSet(FormEvent $event)
 {
     $data = $event->getData();
     if ($data && !$data->getId() && !$data->getDefaultUserOwner() || null === $data) {
         $event->getForm()->get('defaultUserOwner')->setData($this->securityFacade->getLoggedUser());
     }
 }
Exemplo n.º 5
0
 /**
  * Process form
  *
  * @param  CalendarEvent $entity
  * @throws \LogicException
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(CalendarEvent $entity)
 {
     if (!$entity->getCalendar()) {
         if ($this->securityFacade->getLoggedUser() && $this->securityFacade->getOrganization()) {
             /** @var Calendar $defaultCalendar */
             $defaultCalendar = $this->manager->getRepository('OroCalendarBundle:Calendar')->findDefaultCalendar($this->securityFacade->getLoggedUser()->getId(), $this->securityFacade->getOrganization()->getId());
             $entity->setCalendar($defaultCalendar);
         } else {
             throw new \LogicException('Current user did not define');
         }
     }
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             $targetEntityClass = $this->entityRoutingHelper->getEntityClassName($this->request);
             if ($targetEntityClass) {
                 $targetEntityId = $this->entityRoutingHelper->getEntityId($this->request);
                 $targetEntity = $this->entityRoutingHelper->getEntityReference($targetEntityClass, $targetEntityId);
                 $action = $this->entityRoutingHelper->getAction($this->request);
                 if ($action === 'activity') {
                     $this->activityManager->addActivityTarget($entity, $targetEntity);
                 }
                 if ($action === 'assign' && $targetEntity instanceof User && $targetEntityId !== $this->securityFacade->getLoggedUserId()) {
                     /** @var Calendar $defaultCalendar */
                     $defaultCalendar = $this->manager->getRepository('OroCalendarBundle:Calendar')->findDefaultCalendar($targetEntity->getId(), $targetEntity->getOrganization()->getId());
                     $entity->setCalendar($defaultCalendar);
                 }
             }
             $this->onSuccess($entity);
             return true;
         }
     }
     return false;
 }
 /**
  * @param OrmResultBefore $event
  */
 public function onResultBefore(OrmResultBefore $event)
 {
     // listener logic is applied only to frontend part of application
     if ($this->securityFacade->getLoggedUser() instanceof User) {
         return;
     }
     $config = $event->getDatagrid()->getConfig();
     $query = $event->getQuery();
     /** @var Subselect|SelectStatement $select */
     $select = $query->getAST();
     $fromClause = $select instanceof SelectStatement ? $select->fromClause : $select->subselectFromClause;
     $skipAclCheck = true;
     /** @var IdentificationVariableDeclaration $identificationVariableDeclaration */
     foreach ($fromClause->identificationVariableDeclarations as $identificationVariableDeclaration) {
         $entityName = $identificationVariableDeclaration->rangeVariableDeclaration->abstractSchemaName;
         $metadata = $this->metadataProvider->getMetadata($entityName);
         if ($metadata->hasOwner()) {
             $skipAclCheck = false;
             break;
         }
     }
     if ($skipAclCheck) {
         $config->offsetSetByPath(Builder::DATASOURCE_SKIP_ACL_CHECK, true);
     }
 }
Exemplo n.º 7
0
 /**
  * @return User
  */
 protected function getCurrentUser()
 {
     $user = $this->securityFacade->getLoggedUser();
     if ($user instanceof User) {
         return $user;
     }
     return null;
 }
 /**
  * @return AccountUser|null
  */
 public function getLoggedUser()
 {
     $user = $this->securityFacade->getLoggedUser();
     if ($user instanceof AccountUser) {
         return $user;
     }
     return null;
 }
Exemplo n.º 9
0
 /**
  * @return array
  */
 protected function createChoices()
 {
     $user = $this->securityFacade->getLoggedUser();
     if (!$user instanceof User) {
         return [];
     }
     $emails = array_merge(array_values($this->relatedEmailsProvider->getEmails($user, 1, true)), $this->mailboxManager->findAvailableMailboxEmails($user, $this->securityFacade->getOrganization()));
     return array_combine($emails, $emails);
 }
Exemplo n.º 10
0
 /**
  * @return array
  */
 protected function createChoices()
 {
     $user = $this->securityFacade->getLoggedUser();
     if (!$user instanceof User) {
         return [];
     }
     $emails = array_values($this->relatedEmailsProvider->getEmails($user, 1, true));
     return array_combine($emails, $emails);
 }
 /**
  * @return string
  * @throws \RuntimeException
  */
 public function getPrefix()
 {
     $user = $this->securityFacade->getLoggedUser();
     if ($user instanceof User) {
         return self::BACKEND_PREFIX;
     } elseif ($user instanceof AccountUser) {
         return self::FRONTEND_PREFIX;
     }
     throw new \RuntimeException('This method must be called only for logged User or AccountUser');
 }
Exemplo n.º 12
0
 /**
  * Set email seen status for current user for single email or thread
  *
  * @param Email $entity
  * @param bool  $isSeen
  * @param bool  $checkThread - if false it will be applied for single email instead of thread
  */
 public function setSeenStatus(Email $entity, $isSeen = true, $checkThread = false)
 {
     $user = $this->securityFacade->getLoggedUser();
     $organization = $this->securityFacade->getOrganization();
     $emailUsers = $this->getEmailUserRepository()->getAllEmailUsersByEmail($entity, $user, $organization, $checkThread);
     foreach ($emailUsers as $emailUser) {
         $this->setEmailUserSeen($emailUser, $isSeen);
     }
     $this->em->flush();
 }
Exemplo n.º 13
0
 /**
  * @param ResultRecordInterface $record
  * @return array
  */
 public function getInvitationPermissions(ResultRecordInterface $record)
 {
     /** @var User $user */
     $user = $this->securityFacade->getLoggedUser();
     $invitationStatus = $record->getValue('invitationStatus');
     $parentId = $record->getValue('parentId');
     $ownerId = $record->getValue('ownerId');
     $childrenCount = $record->getValue('childrenCount');
     $isEditable = !$invitationStatus || $invitationStatus && !$parentId;
     return array('accept' => $this->isAvailableResponseButton($user, $parentId, $ownerId, $childrenCount, $invitationStatus, CalendarEvent::ACCEPTED), 'decline' => $this->isAvailableResponseButton($user, $parentId, $ownerId, $childrenCount, $invitationStatus, CalendarEvent::DECLINED), 'tentatively' => $this->isAvailableResponseButton($user, $parentId, $ownerId, $childrenCount, $invitationStatus, CalendarEvent::TENTATIVELY_ACCEPTED), 'view' => true, 'update' => $isEditable);
 }
 /**
  * @param FormEvent $event
  * @return bool
  */
 public function onPreSetData(FormEvent $event)
 {
     /** @var $user AccountUser */
     $user = $this->securityFacade->getLoggedUser();
     if (!$user instanceof AccountUser) {
         return;
     }
     $account = $user->getAccount();
     /** @var AccountUser $data */
     $data = $event->getData();
     $data->setAccount($account);
 }
Exemplo n.º 15
0
 /**
  * @param User $entity
  *
  * {@inheritdoc}
  */
 public function hasAccessEditField($entity, $fieldName)
 {
     if (!$entity instanceof User) {
         $className = ClassUtils::getClass($entity);
         throw new IncorrectEntityException(sprintf('Entity %s, is not instance of User class', $className));
     }
     $currentUser = $this->securityFacade->getLoggedUser();
     if ($this->hasField($entity, $fieldName) && in_array($fieldName, $this->getCurrentUserFieldBlockList(), true) && $currentUser->getId() !== $entity->getId()) {
         return true;
     }
     return $this->hasField($entity, $fieldName) && !in_array($fieldName, $this->getCurrentUserFieldBlockList(), true);
 }
Exemplo n.º 16
0
 /**
  * Gets a list of user's calendars for which it is granted to add events
  *
  * @return array of [id, name]
  */
 public function getUserCalendars()
 {
     /** @var CalendarRepository $repo */
     $repo = $this->doctrineHelper->getEntityRepository('OroCalendarBundle:Calendar');
     $calendars = $repo->getUserCalendarsQueryBuilder($this->securityFacade->getOrganizationId(), $this->securityFacade->getLoggedUserId())->select('c.id, c.name')->getQuery()->getArrayResult();
     foreach ($calendars as &$calendar) {
         if (empty($calendar['name'])) {
             $calendar['name'] = $this->entityNameResolver->getName($this->securityFacade->getLoggedUser());
         }
     }
     return $calendars;
 }
 /**
  * @param bool $addValue FALSE for variable definitions; TRUE for variable values
  *
  * @return array
  */
 protected function getVariables($addValue)
 {
     $result = [];
     $organization = $this->securityFacade->getOrganization();
     $user = $this->securityFacade->getLoggedUser();
     $this->addOrganizationName($result, $organization, $addValue);
     $this->addUserName($result, $user, $addValue);
     $this->addUserFirstName($result, $user, $addValue);
     $this->addUserLastName($result, $user, $addValue);
     $this->addUserFullName($result, $user, $addValue);
     return $result;
 }
 /**
  * @param ResultRecordInterface $record
  *
  * @return array
  */
 public function getUserPermissions(ResultRecordInterface $record)
 {
     $disabled = $enabled = $record->getValue('enabled');
     $user = $this->securityFacade->getLoggedUser();
     $delete = true;
     if ($user instanceof AccountUser) {
         $isCurrentUser = $user->getId() == $record->getValue('id');
         $disabled = $isCurrentUser ? false : $enabled;
         $delete = !$isCurrentUser;
     }
     return ['enable' => !$enabled, 'disable' => $disabled, 'view' => true, 'update' => true, 'delete' => $delete];
 }
 /**
  * @param BuildBefore $event
  */
 public function onBuildBefore(BuildBefore $event)
 {
     $config = $event->getConfig();
     $user = $this->securityFacade->getLoggedUser();
     if ($user instanceof AccountUser && $user->getAccount() && $this->securityFacade->isGranted('orob2b_account_frontend_account_user_role_view')) {
         $andWhere = 'role.account IN (' . $user->getAccount()->getId() . ')';
         $this->addConfigElement($config, '[source][query][where][and]', $andWhere);
         $orWhere = 'role.account IS NULL';
         $this->addConfigElement($config, '[source][query][where][or]', $orWhere);
     } else {
         $this->addConfigElement($config, '[source][query][where][and]', '1=0');
     }
 }
 /**
  * @param FilterControllerEvent $event
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     $env = $this->container->getParameter("kernel.environment");
     $user = $this->securityFacade->getLoggedUser();
     if ('test' == $env && $user instanceof ApiUser) {
         $em = $this->container->get('doctrine.orm.entity_manager');
         $eventManager = $em->getEventManager();
         foreach ($eventManager->getListeners()['onFlush'] as $hash => $listener) {
             if ($listener instanceof EntityListener) {
                 $eventManager->removeEventListener('onFlush', $listener);
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function configureOptions(OptionsResolver $resolver)
 {
     $loggedUser = $this->securityFacade->getLoggedUser();
     if (!$loggedUser instanceof AccountUser) {
         return;
     }
     $resolver->setNormalizer('loader', function () use($loggedUser) {
         /** @var $repo AccountUserRoleRepository */
         $repo = $this->registry->getManagerForClass($this->roleClass)->getRepository($this->roleClass);
         /** @var  $qb QueryBuilder */
         $qb = $repo->getAvailableRolesByAccountUserQueryBuilder($loggedUser);
         return new ORMQueryBuilderLoader($qb);
     });
 }
Exemplo n.º 22
0
 /**
  * Apply custom ACL checks
  *
  * @param QueryBuilder $qb
  */
 public function applyAcl(QueryBuilder $qb)
 {
     $user = $this->securityFacade->getLoggedUser();
     $organization = $this->securityFacade->getOrganization();
     $mailboxIds = $this->doctrine->getRepository('OroEmailBundle:Mailbox')->findAvailableMailboxIds($user, $organization);
     $uoCheck = $qb->expr()->andX($qb->expr()->eq('eu.owner', ':owner'), $qb->expr()->eq('eu.organization ', ':organization'));
     if (!empty($mailboxIds)) {
         $qb->andWhere($qb->expr()->orX($uoCheck, $qb->expr()->in('eu.mailboxOwner', ':mailboxIds')));
         $qb->setParameter('mailboxIds', $mailboxIds);
     } else {
         $qb->andWhere($uoCheck);
     }
     $qb->setParameter('owner', $user->getId());
     $qb->setParameter('organization', $organization->getId());
 }
 /**
  * @param string $permission
  * @return string
  */
 protected function getPermission($permission)
 {
     if (!$this->securityFacade->getLoggedUser() instanceof AccountUser) {
         $permission .= OrderAddressProvider::ADMIN_ACL_POSTFIX;
     }
     return $permission;
 }
Exemplo n.º 24
0
 /**
  * @param FormBuilderInterface $builder
  */
 protected function addOwnerOrganizationEventListener(FormBuilderInterface $builder)
 {
     $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
         /** @var ImapEmailOrigin $data */
         $data = $event->getData();
         if ($data !== null) {
             if ($data->getOwner() === null) {
                 $data->setOwner($this->securityFacade->getLoggedUser());
             }
             if ($data->getOrganization() === null) {
                 $organization = $this->securityFacade->getOrganization() ? $this->securityFacade->getOrganization() : $this->securityFacade->getLoggedUser()->getOrganization();
                 $data->setOrganization($organization);
             }
             $event->setData($data);
         }
     });
 }
 /**
  * @param string $type
  * @param string $key
  * @return string
  */
 protected function getPermission($type, $key)
 {
     $postfix = '';
     if (!$this->securityFacade->getLoggedUser() instanceof AccountUser) {
         $postfix = self::ADMIN_ACL_POSTFIX;
     }
     return $this->permissionsByType[$type][$key] . $postfix;
 }
Exemplo n.º 26
0
 /**
  * Return array of numbers unread emails per folder
  *
  * @return array
  */
 public function getUnreadEmailsCount()
 {
     $currentOrganization = $this->securityFacade->getOrganization();
     $currentUser = $this->securityFacade->getLoggedUser();
     $result = $this->em->getRepository("OroEmailBundle:Email")->getCountNewEmailsPerFolders($currentUser, $currentOrganization);
     $total = $this->em->getRepository("OroEmailBundle:Email")->getCountNewEmails($currentUser, $currentOrganization);
     $result[] = array('num' => $total, 'id' => 0);
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 public function getRecipients(EmailRecipientsProviderArgs $args)
 {
     if (null === ($user = $this->securityFacade->getLoggedUser())) {
         return [];
     }
     $userEmailAddresses = array_keys($this->relatedEmailsProvider->getEmails($user, 1, true));
     $recipientsQb = $this->getEmailRecipientRepository()->getEmailsUsedInLast30DaysQb($userEmailAddresses, [], $args->getQuery())->setMaxResults($args->getLimit());
     $emails = $this->emailsFromResult($this->aclHelper->apply($recipientsQb)->getResult());
     $result = [];
     foreach ($emails as $email => $name) {
         $owner = $this->emailOwnerProvider->findEmailOwner($this->registry->getManager(), $email);
         if (!$this->emailRecipientsHelper->isObjectAllowed($args, $owner)) {
             continue;
         }
         $result[] = new Recipient($email, $name, $this->createRecipientEntity($owner));
     }
     return $result;
 }
Exemplo n.º 28
0
 /**
  * Gets defined as default grid view for current logged user.
  *
  * @param string $gridName
  *
  * @return GridView|null
  */
 protected function getDefaultView($gridName)
 {
     if ($this->defaultGridView === false) {
         $repository = $this->registry->getRepository('OroDataGridBundle:GridView');
         $defaultGridView = $repository->findDefaultGridView($this->aclHelper, $this->securityFacade->getLoggedUser(), $gridName);
         $this->defaultGridView = $defaultGridView;
     }
     return $this->defaultGridView;
 }
Exemplo n.º 29
0
 /**
  * Returns array of mailbox choices.
  *
  * @return array
  */
 public function getChoiceList()
 {
     /** @var Mailbox[] $systemMailboxes */
     $systemMailboxes = $this->mailboxManager->findAvailableMailboxes($this->securityFacade->getLoggedUser(), $this->getOrganization());
     $origins = $this->mailboxManager->findAvailableOrigins($this->securityFacade->getLoggedUser(), $this->getOrganization());
     $choiceList = [];
     foreach ($origins as $origin) {
         $mailbox = $origin->getMailboxName();
         if (count($origin->getFolders()) > 0) {
             $choiceList[$origin->getId()] = str_replace('@', '\\@', $mailbox);
         }
     }
     foreach ($systemMailboxes as $mailbox) {
         if ($mailbox->getOrigin() !== null) {
             $choiceList[$mailbox->getOrigin()->getId()] = $mailbox->getLabel();
         }
     }
     return $choiceList;
 }
Exemplo n.º 30
0
 /**
  * @return null|User
  */
 protected function getCurrentUser()
 {
     if (null === $this->currentUser) {
         $user = $this->securityFacade->getLoggedUser();
         if ($user && !is_string($user)) {
             $this->currentUser = $user;
         }
     }
     return $this->currentUser;
 }