/** * Build business units tree for user page * * @param User $user * @return array */ public function getBusinessUnitsTree(User $user = null) { $businessUnits = $this->createQueryBuilder('businessUnit')->select(array('businessUnit.id', 'businessUnit.name', 'IDENTITY(businessUnit.owner) parent')); if ($user && $user->getId()) { $units = $user->getBusinessUnits()->map(function (BusinessUnit $businessUnit) { return $businessUnit->getId(); }); $units = $units->toArray(); if ($units) { $businessUnits->addSelect('CASE WHEN businessUnit.id IN (:userUnits) THEN 1 ELSE 0 END as hasUser'); $businessUnits->setParameter(':userUnits', $units); } } $businessUnits = $businessUnits->getQuery()->getArrayResult(); $children = array(); foreach ($businessUnits as &$businessUnit) { $parent = $businessUnit['parent'] ?: 0; $children[$parent][] =& $businessUnit; } unset($businessUnit); foreach ($businessUnits as &$businessUnit) { if (isset($children[$businessUnit['id']])) { $businessUnit['children'] = $children[$businessUnit['id']]; } } unset($businessUnit); if (isset($children[0])) { $children = $children[0]; } return $children; }
/** * Test new user creation */ public function testOnFlushCreateUser() { $args = new OnFlushEventArgs($this->em); $user = new User(); $org1 = new Organization(); ReflectionUtil::setId($org1, 1); $org2 = new Organization(); ReflectionUtil::setId($org2, 2); $user->setOrganization($org1); $user->addOrganization($org1); $user->addOrganization($org2); $newCalendar1 = new Calendar(); $newCalendar1->setOwner($user)->setOrganization($org1); $newCalendar2 = new Calendar(); $newCalendar2->setOwner($user)->setOrganization($org2); $calendarMetadata = new ClassMetadata(get_class($newCalendar1)); $this->uow->expects($this->once())->method('getScheduledEntityInsertions')->will($this->returnValue([$user])); $this->uow->expects($this->once())->method('getScheduledCollectionUpdates')->will($this->returnValue([])); $this->em->expects($this->at(1))->method('persist')->with($this->equalTo($newCalendar1)); $this->em->expects($this->at(2))->method('getClassMetadata')->with('Oro\\Bundle\\CalendarBundle\\Entity\\Calendar')->will($this->returnValue($calendarMetadata)); $this->em->expects($this->at(3))->method('persist')->with($this->equalTo($newCalendar2)); $this->uow->expects($this->at(1))->method('computeChangeSet')->with($calendarMetadata, $newCalendar1); $this->uow->expects($this->at(2))->method('computeChangeSet')->with($calendarMetadata, $newCalendar2); $this->listener->onFlush($args); }
/** * @Route("/connection/check", name="oro_imap_connection_check", methods={"POST"}) */ public function checkAction() { $responseCode = Codes::HTTP_BAD_REQUEST; $data = null; $id = $this->getRequest()->get('id', false); if (false !== $id) { $data = $this->getDoctrine()->getRepository('OroImapBundle:ImapEmailOrigin')->find($id); } $form = $this->createForm('oro_imap_configuration', null, ['csrf_protection' => false, 'validation_groups' => ['Check']]); $form->setData($data); $form->submit($this->getRequest()); /** @var ImapEmailOrigin $origin */ $origin = $form->getData(); if ($form->isValid() && null !== $origin) { $config = new ImapConfig($origin->getHost(), $origin->getPort(), $origin->getSsl(), $origin->getUser(), $this->get('oro_security.encoder.mcrypt')->decryptData($origin->getPassword())); try { $connector = $this->get('oro_imap.connector.factory')->createImapConnector($config); $this->manager = new ImapEmailFolderManager($connector, $this->getDoctrine()->getManager(), $origin); $emailFolders = $this->manager->getFolders(); $origin->setFolders($emailFolders); $user = new User(); $user->setImapConfiguration($origin); $userForm = $this->get('oro_user.form.user'); $userForm->setData($user); return $this->render('OroImapBundle:Connection:check.html.twig', ['form' => $userForm->createView()]); } catch (\Exception $e) { $this->get('logger')->critical('Unable to connect to IMAP server: ' . $e->getMessage(), ['exception' => $e]); } } return new Response('', $responseCode); }
/** * @Route("/connection/check", name="oro_imap_connection_check", methods={"POST"}) */ public function checkAction(Request $request) { $responseCode = Codes::HTTP_BAD_REQUEST; $data = null; $id = $request->get('id', false); if (false !== $id) { $data = $this->getDoctrine()->getRepository('OroImapBundle:UserEmailOrigin')->find($id); } $form = $this->createForm('oro_imap_configuration', null, ['csrf_protection' => false]); $form->setData($data); $form->submit($request); /** @var UserEmailOrigin $origin */ $origin = $form->getData(); if ($form->isValid() && null !== $origin) { $response = []; $password = $this->get('oro_security.encoder.mcrypt')->decryptData($origin->getPassword()); if ($origin->getImapHost() !== null) { $response['imap'] = []; $config = new ImapConfig($origin->getImapHost(), $origin->getImapPort(), $origin->getImapEncryption(), $origin->getUser(), $password); try { $connector = $this->get('oro_imap.connector.factory')->createImapConnector($config); $this->manager = new ImapEmailFolderManager($connector, $this->getDoctrine()->getManager(), $origin); $emailFolders = $this->manager->getFolders(); $origin->setFolders($emailFolders); if ($request->get('for_entity', 'user') === 'user') { $user = new User(); $user->setImapConfiguration($origin); $userForm = $this->get('oro_user.form.user'); $userForm->setData($user); $response['imap']['folders'] = $this->renderView('OroImapBundle:Connection:check.html.twig', ['form' => $userForm->createView()]); } elseif ($request->get('for_entity', 'user') === 'mailbox') { $mailbox = new Mailbox(); $mailbox->setOrigin($origin); $mailboxForm = $this->createForm('oro_email_mailbox'); $mailboxForm->setData($mailbox); $response['imap']['folders'] = $this->renderView('OroImapBundle:Connection:checkMailbox.html.twig', ['form' => $mailboxForm->createView()]); } } catch (\Exception $e) { $response['imap']['error'] = $e->getMessage(); } } if ($origin->getSmtpHost() !== null) { $response['smtp'] = []; try { $mailer = $this->get('oro_email.direct_mailer'); $transport = $mailer->getTransport(); $transport->setHost($origin->getSmtpHost()); $transport->setPort($origin->getSmtpPort()); $transport->setEncryption($origin->getSmtpEncryption()); $transport->setUsername($origin->getUser()); $transport->setPassword($password); $transport->start(); } catch (\Exception $e) { $response['smtp']['error'] = $e->getMessage(); } } return new JsonResponse($response); } return new Response('', $responseCode); }
/** * Test add and remove activity owner from ActivityList */ public function testAddRemoveActivityOwner() { $activity = new ActivityList(); $activity->setId(1); $organization = new Organization(); $user1 = new User(); $user1->setId(1); $user1->setFirstName('TestUserName1'); $entity1 = new ActivityOwner(); $entity1->setActivity($activity); $entity1->setUser($user1); $entity1->setOrganization($organization); $activity->addActivityOwner($entity1); $user2 = new User(); $user1->setId(2); $user2->setFirstName('TestUserName2'); $entity2 = new ActivityOwner(); $entity2->setActivity($activity); $entity2->setUser($user2); $entity2->setOrganization($organization); $activity->addActivityOwner($entity2); $this->assertTrue($activity->getActivityOwners()->contains($entity1)); $this->assertTrue($activity->getActivityOwners()->contains($entity2)); $activity->removeActivityOwner($entity1); $activity->removeActivityOwner($entity2); $this->assertFalse($activity->getActivityOwners()->contains($entity1)); $this->assertFalse($activity->getActivityOwners()->contains($entity2)); }
public function testProcessValidData() { $appendedUser = new User(); $appendedUser->setId(1); $removedUser = new User(); $removedUser->setId(2); $removedUser->addBusinessUnit($this->entity); $this->form->expects($this->once())->method('setData')->with($this->entity); $this->form->expects($this->once())->method('submit')->with($this->request); $this->request->setMethod('POST'); $this->form->expects($this->once())->method('isValid')->will($this->returnValue(true)); $appendForm = $this->getMockBuilder('Symfony\\Component\\Form\\Form')->disableOriginalConstructor()->getMock(); $appendForm->expects($this->once())->method('getData')->will($this->returnValue(array($appendedUser))); $this->form->expects($this->at(3))->method('get')->with('appendUsers')->will($this->returnValue($appendForm)); $removeForm = $this->getMockBuilder('Symfony\\Component\\Form\\Form')->disableOriginalConstructor()->getMock(); $removeForm->expects($this->once())->method('getData')->will($this->returnValue(array($removedUser))); $this->form->expects($this->at(4))->method('get')->with('removeUsers')->will($this->returnValue($removeForm)); $this->manager->expects($this->at(0))->method('persist')->with($appendedUser); $this->manager->expects($this->at(1))->method('persist')->with($removedUser); $this->manager->expects($this->at(2))->method('persist')->with($this->entity); $this->manager->expects($this->once())->method('flush'); $this->assertTrue($this->handler->process($this->entity)); $businessUnits = $appendedUser->getBusinessUnits()->toArray(); $this->assertCount(1, $businessUnits); $this->assertEquals($this->entity, current($businessUnits)); $this->assertCount(0, $removedUser->getBusinessUnits()->toArray()); }
/** * Test existing user modification */ public function testOnFlushUpdateUser() { $args = new OnFlushEventArgs($this->em); $user = new User(); $org = new Organization(); $org->setId(1); $org->setName('test'); $user->addOrganization($org); $newCalendar = new Calendar(); $newCalendar->setOwner($user); $newCalendar->setOrganization($org); $newConnection = new CalendarConnection($newCalendar); $newCalendar->addConnection($newConnection); $calendarMetadata = new ClassMetadata(get_class($newCalendar)); $connectionMetadata = new ClassMetadata(get_class($newConnection)); $this->em->expects($this->any())->method('getClassMetadata')->will($this->returnValueMap([['Oro\\Bundle\\CalendarBundle\\Entity\\Calendar', $calendarMetadata], ['Oro\\Bundle\\CalendarBundle\\Entity\\CalendarConnection', $connectionMetadata]])); $calendarRepo = $this->getMockBuilder('\\Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock(); $calendarRepo->expects($this->any())->method('findDefaultCalendar')->will($this->returnValue(false)); $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($this->uow)); $this->uow->expects($this->once())->method('getScheduledEntityInsertions')->will($this->returnValue([])); $this->uow->expects($this->once())->method('getScheduledEntityUpdates')->will($this->returnValue([$user])); $this->em->expects($this->any())->method('getRepository')->with('OroCalendarBundle:Calendar')->will($this->returnValue($calendarRepo)); $this->em->expects($this->at(2))->method('persist')->with($this->equalTo($newCalendar)); $this->em->expects($this->at(3))->method('persist')->with($this->equalTo($newConnection)); $this->uow->expects($this->at(2))->method('computeChangeSet')->with($calendarMetadata, $newCalendar); $this->uow->expects($this->at(3))->method('computeChangeSet')->with($connectionMetadata, $newConnection); $this->listener->onFlush($args); }
public function testGetActivityOwners() { $organization = new Organization(); $organization->setName('Org'); $user = new User(); $user->setUsername('test'); $emailUser = new EmailUser(); $emailUser->setOrganization($organization); $emailUser->setOwner($user); $owners = [$emailUser]; $emailMock = $this->getMockBuilder('Oro\\Bundle\\EmailBundle\\Entity\\EmailUser')->setMethods(['getFromEmailAddress', 'hasOwner', 'getOwner', 'getOrganization', 'getActivityTargetEntities'])->disableOriginalConstructor()->getMock(); $emailMock->expects($this->once())->method('getFromEmailAddress')->willReturn($emailMock); $emailMock->expects($this->once())->method('getOwner')->willReturn($emailMock); $emailMock->expects($this->exactly(2))->method('getOrganization')->willReturn($organization); $emailMock->expects($this->exactly(1))->method('getActivityTargetEntities')->willReturn([]); $activityListMock = $this->getMockBuilder('Oro\\Bundle\\ActivityListBundle\\Entity\\ActivityList')->disableOriginalConstructor()->getMock(); $em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock(); $repository = $this->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock(); $this->doctrineRegistryLink->expects($this->once())->method('getService')->willReturn($em); $em->expects($this->once())->method('getRepository')->willReturn($repository); $repository->expects($this->once())->method('findBy')->willReturn($owners); $activityOwnerArray = $this->emailActivityListProvider->getActivityOwners($emailMock, $activityListMock); $this->assertCount(1, $activityOwnerArray); $owner = $activityOwnerArray[0]; $this->assertEquals($organization->getName(), $owner->getOrganization()->getName()); $this->assertEquals($user->getUsername(), $owner->getUser()->getUsername()); }
/** * @param User $currentUser * @param GridView $gridView * * @return string */ protected function createGridViewLabel(User $currentUser, GridView $gridView) { if ($gridView->getOwner()->getId() === $currentUser->getId()) { return $gridView->getName(); } return $this->translator->trans('oro.datagrid.gridview.shared_by', ['%name%' => $gridView->getName(), '%owner%' => $gridView->getOwner()->getUsername()]); }
/** * Set status as current * * @param User $user * @param Status $status * @param bool $reloadUser */ public function setCurrentStatus(User $user, Status $status = null, $reloadUser = true) { $user->setCurrentStatus($status); $this->um->updateUser($user); if ($reloadUser) { $this->um->reloadUser($user); } }
/** * Updates a user password if a plain password is set * * @param User $user */ public function updatePassword(User $user) { if (0 !== strlen($password = $user->getPlainPassword())) { $encoder = $this->getEncoder($user); $user->setPassword($encoder->encodePassword($password, $user->getSalt())); $user->eraseCredentials(); } }
/** * @return array */ public function dataProvider() { $object = new \stdClass(); $userDisabled = new User(); $userDisabled->setEnabled(false); $userEnabled = new User(); return [[null, false], [$object, false], [$userDisabled, false], [$userEnabled, true]]; }
public function testToStringUsername() { $obj = new Calendar(); $owner = new User(); $owner->setUsername('testUsername'); $obj->setOwner($owner); $this->assertEquals($owner->getUsername(), (string) $obj); }
/** * @depends testCreate * @param integer $id * @return array */ public function testGet($id) { $result = $this->soapClient->getPartner($id); $partner = $this->valueToArray($result); $this->assertArrayIntersectEquals(['id' => $id, 'partnerCondition' => $this->partnerCreateData['partnerCondition'], 'status' => $this->partnerCreateData['status'], 'account' => $this->getReference('orocrm_partner:test_account_1')->getId(), 'owner' => $this->adminUser->getId()], $partner); $this->assertArrayHasKey('startDate', $partner); $this->assertNotEmpty($partner['startDate']); return $partner; }
public function testSetUsername() { $user = new User(); $user->setUsername('testuser'); $this->loggableManager->setUsername($user); $this->setExpectedException('InvalidArgumentException', 'Username must be a string, or object should have method: getUsername'); $wrongUser = new \stdClass(); $this->loggableManager->setUsername($wrongUser); }
/** * Returns true if passed user is currently authenticated * * @param User $user * @return bool */ protected function isCurrentUser(User $user) { $token = $this->security->getToken(); $currentUser = $token ? $token->getUser() : null; if ($user->getId() && is_object($currentUser)) { return $currentUser->getId() == $user->getId(); } return false; }
/** * @param User $entity * @param array $businessUnits */ public function assignBusinessUnits($entity, array $businessUnits) { if ($businessUnits) { $businessUnits = $this->getBusinessUnitRepo()->getBusinessUnits($businessUnits); } else { $businessUnits = new ArrayCollection(); } $entity->setBusinessUnits($businessUnits); }
public function testInitializeScopeId() { $user = new User(); $user->setId(123); $token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface'); $this->securityContext->expects($this->once())->method('getToken')->willReturn($token); $token->expects($this->once())->method('getUser')->willReturn($user); $this->assertEquals(123, $this->manager->getScopeId()); }
public function testGetPermissionsWithEntities() { $this->client->request('GET', $this->getUrl('oro_api_get_user_permissions', ['id' => $this->user->getId(), 'entities' => 'Oro\\Bundle\\UserBundle\\Entity\\User'])); $result = $this->getJsonResponseContent($this->client->getResponse(), 200); $this->assertCount(1, $result, "Result should contains only permissions for one entity"); $this->client->request('GET', $this->getUrl('oro_api_get_user_permissions', ['id' => $this->user->getId(), 'entities' => implode(',', ['user', 'Oro\\Bundle\\OrganizationBundle\\Entity\\Organization'])])); $result = $this->getJsonResponseContent($this->client->getResponse(), 200); $this->assertCount(2, $result, "Result should contains only permissions for two entities"); }
/** * Add the default group to the user. * * @param User $user * * @throws \RuntimeException */ protected function addDefaultGroup(User $user) { if (!$user->hasGroup(User::GROUP_DEFAULT)) { $group = $this->manager->getStorageManager()->getRepository('OroUserBundle:Group')->getDefaultUserGroup(); if (!$group) { throw new \RuntimeException('Default user group not found'); } $user->addGroup($group); } }
/** * @test */ public function userFullNameRetrieves() { $firstname = 'First'; $lastname = 'Last'; $user = new User(); $user->setFirstName($firstname); $user->setLastName($lastname); $worklog = new Worklog(new TimeSpent(50), new \DateTime('now'), new Task(), $user, 'DUMMY_DESCRIPTION'); $this->assertEquals(sprintf('%s %s', $firstname, $lastname), $worklog->getUserFullName()); }
/** * @param string $key * @param User $entity */ public function fillEntityData($key, $entity) { $businessUnitRepo = $this->templateManager->getEntityRepository('Oro\\Bundle\\OrganizationBundle\\Entity\\BusinessUnit'); switch ($key) { case 'John Doo': $entity->setUsername('admin')->setLoginCount(101)->setId(1)->setPlainPassword('admin_password')->setFirstname('John')->setMiddleName('Awesome')->setLastname('Doe')->setEmail('*****@*****.**')->setNamePrefix('Mr.')->setNameSuffix('Jr.')->setBirthday(new \DateTime('2013-02-01'))->setCreatedAt(new \DateTime())->setUpdatedAt(new \DateTime())->setEnabled(true)->setOwner($businessUnitRepo->getEntity('Main'))->addGroup(new Group('Administrators'))->addBusinessUnit($businessUnitRepo->getEntity('Main')); return; } parent::fillEntityData($key, $entity); }
public function testProcessEvent() { $user = new User(); $user->setId(1); $this->configManager->expects($this->once())->method('get')->with('diamante_desk.email_notification')->will($this->returnValue(true)); $this->securityFacade->expects($this->once())->method('getLoggedUser')->will($this->returnValue($user)); $event = $this->event(); $this->notificationDeliveryManager->expects($this->once())->method('add')->with($this->logicalAnd($this->isInstanceOf('\\Diamante\\DeskBundle\\Model\\Ticket\\Notifications\\TicketNotification'), $this->attributeEqualTo('ticketUniqueId', $event->getAggregateId()), $this->attributeEqualTo('author', $user), $this->attributeEqualTo('headerText', $event->getHeaderText()), $this->attributeEqualTo('subject', $event->getSubject()), $this->attributeEqualTo('attachments', $event->attachments()), $this->attribute($this->logicalAnd($this->isInstanceOf('\\ArrayIterator'), $this->arrayHasKey('Description'), $this->contains('New Description')), 'changeList'))); $this->subscriber->processEvent($event); }
/** * @Route("/apigen/{id}", name="oro_user_apigen", requirements={"id"="\d+"}) * @AclAncestor("oro_user_user_update") */ public function apigenAction(User $user) { if (!($api = $user->getApi())) { $api = new UserApi(); } $api->setApiKey($api->generateKey())->setUser($user); $em = $this->getDoctrine()->getManager(); $em->persist($api); $em->flush(); return $this->getRequest()->isXmlHttpRequest() ? new JsonResponse($api->getApiKey()) : $this->forward('OroUserBundle:User:view', array('user' => $user)); }
/** * @dataProvider hasAccessEditFiledDataProvider * * @param int $currentUserId * @param int $userId * @param string $fieldName * @param bool $result */ public function testHasAccessEditField($currentUserId, $userId, $fieldName, $result) { $currentUser = $this->getMockBuilder('Oro\\Bundle\\UserBundle\\Entity\\User')->setMethods(['getId'])->disableOriginalConstructor()->getMock(); if ('enabled' === $fieldName) { $currentUser->expects(self::once())->method('getId')->willReturn($currentUserId); } $this->securityFacade->expects(self::once())->method('getLoggedUser')->willReturn($currentUser); $entity = new User(); $entity->setId($userId); self::assertEquals($this->validator->hasAccessEditField($entity, $fieldName), $result); }
public function testNewItem() { $user = new User(); $user->setEmail('*****@*****.**'); $this->factory->expects($this->once())->method('createItem')->will($this->returnValue($this->item)); $repository = $this->getDefaultRepositoryMock(null); $em = $this->getEntityManager($repository); $listener = $this->getListener($this->factory, $this->securityContext, $em); $response = $this->getResponse(); $listener->onResponse($this->getEventMock($this->getRequest(), $response)); }
/** * @param Crawler $crawler * @param User $owner */ protected function assertOrderSave(Crawler $crawler, User $owner) { $form = $crawler->selectButton('Save and Close')->form(['orob2b_order_type[owner]' => $owner->getId()]); $this->client->followRedirects(true); $crawler = $this->client->submit($form); $result = $this->client->getResponse(); $this->assertHtmlResponseStatusCodeEquals($result, 200); $html = $crawler->html(); $this->assertContains('Order has been saved', $html); $this->assertViewPage($crawler, $owner); }
/** * @depends testPost * @param integer $id * @return array */ public function testGet($id) { $this->client->request('GET', $this->getUrl('orocrm_partner_api_get_partner', ['id' => $id]), [], [], $this->generateWsseAuthHeader()); $partner = $this->getJsonResponseContent($this->client->getResponse(), 200); $this->assertArrayIntersectEquals(['partnerCondition' => $this->partnerPostData['partnerCondition'], 'status' => $this->partnerPostData['status'], 'account' => $this->partnerPostData['account'], 'owner' => $this->adminUser->getId()], $partner); $this->assertArrayHasKey('startDate', $partner); $this->assertNotEmpty($partner['startDate']); $this->assertArrayHasKey('id', $partner); $this->assertGreaterThan(0, $partner['id']); return $partner; }
public function testSendNotNewEntity() { $organization = new Organization(); $organization->setId(1); $user = new User(); $user->setId(1); $this->emailUser->expects($this->exactly(1))->method('getOwner')->willReturn($user); $this->emailUser->expects($this->exactly(2))->method('getOrganization')->willReturn($organization); $this->topicPublisher->expects($this->once())->method('send')->with(WebSocketSendProcessor::getUserTopic($this->emailUser->getOwner(), $this->emailUser->getOrganization()), json_encode(['hasNewEmail' => false])); $this->processor->send([1 => ['entity' => $this->emailUser, 'new' => 0]]); }
/** * @param User $user * @param Organization $organization * @param array $folderTypes * @param bool $isSeen * @return array */ public function getEmailUserList(User $user, Organization $organization, array $folderTypes = [], $isSeen = null) { $qb = $this->createQueryBuilder('eu'); $qb->join('eu.folders', 'f')->join('f.origin', 'o')->andWhere($qb->expr()->eq('eu.owner', $user->getId()))->andWhere($qb->expr()->eq('eu.organization', $organization->getId()))->andWhere($qb->expr()->eq('o.isActive', ':active'))->setParameter('active', true); if ($folderTypes) { $qb->andWhere($qb->expr()->in('f.type', $folderTypes)); } if ($isSeen !== null) { $qb->andWhere($qb->expr()->eq('eu.seen', ':seen'))->setParameter('seen', (bool) $isSeen); } return $qb->getQuery()->getResult(); }