src/Aqarmap/Bundle/UserBundle/Controller/UserController.php line 255
<?php
namespace Aqarmap\Bundle\UserBundle\Controller;
use Aqarmap\Bundle\FeatureToggleBundle\Service\FeatureToggleManager;
use Aqarmap\Bundle\ListingBundle\Entity\Location;
use Aqarmap\Bundle\ListingBundle\Entity\PropertyType;
use Aqarmap\Bundle\ListingBundle\Entity\Section;
use Aqarmap\Bundle\ListingBundle\Form\QuickLeadType;
use Aqarmap\Bundle\ListingBundle\Service\FavouriteService;
use Aqarmap\Bundle\ListingBundle\Service\LocationManager;
use Aqarmap\Bundle\ListingBundle\Service\TopCustomerService;
use Aqarmap\Bundle\NotifierBundle\Service\V3\NotifierSubscriptionService;
use Aqarmap\Bundle\UserBundle\Constant\UserInterestStatus;
use Aqarmap\Bundle\UserBundle\Entity\User;
use Aqarmap\Bundle\UserBundle\Entity\UserInterest;
use Aqarmap\Bundle\UserBundle\Form\QuickRegistrationFormType;
use Aqarmap\Bundle\UserBundle\Services\GoogleUserManager;
use Aqarmap\Bundle\UserBundle\Services\UserActivityService;
use Aqarmap\Bundle\UserBundle\Services\UserManager;
use Aqarmap\Bundle\UserBundle\Services\V3\UserAuthenticationService as UserAuthenticationServiceV3;
use Doctrine\ORM\EntityManagerInterface;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\UserBundle\Model\UserManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
#[Route(path: '/user')]
class UserController extends AbstractController
{
public function __construct(private readonly EntityManagerInterface $entityManager, private readonly PaginatorInterface $paginator, TokenStorageInterface $tokenStorage, private readonly FeatureToggleManager $featureToggleManager, private readonly TranslatorInterface $translator, private readonly TopCustomerService $topCustomerService, private readonly FavouriteService $favouriteService, private readonly LocationManager $locationManager, private readonly UserActivityService $userActivityService, private readonly NotifierSubscriptionService $notifierSubscriptionService, private readonly UserManagerInterface $fosUserManager, private readonly UserManager $userManager, private readonly GoogleUserManager $googleUserManager, private readonly UserAuthenticationServiceV3 $userAuthenticationServiceV3, private readonly \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface $usageTrackingTokenStorage, private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry)
{
}
/**
* User listings.
*
* @return array|RedirectResponse|Response
*
* @throws \Exception
*/
#[Route(path: '/{id}/{type}/{location}', name: 'aqarmap_user_listings', requirements: ['id' => '\d+', 'type' => 'agent|company|', 'location' => '.+[^/]'])]
#[Route(path: '/{id}/{location}', name: 'aqarmap_user_listings_without_type', requirements: ['id' => '\d+', 'location' => '.+[^/]'])]
public function index(int $id, Request $request, #[MapEntity(mapping: ['location' => 'slug'])] ?Location $location = null, ?string $type = null)
{
$em = $this->entityManager;
$user = $em->getRepository(User::class)->find($id);
if (!$user) {
throw new NotFoundHttpException('User Not Found');
}
$pageNumber = max($request->query->getInt('page', 1), 1);
if (1 == $request->query->getInt('page')) {
return $this->redirectToFirstPage($request, $user, $location);
}
$isAgentProfileToggled = $this->featureToggleManager
->isEnabled('web.agents.section');
$isTopCustomer = $this->topCustomerService->isTopCustomer($user) && $isAgentProfileToggled;
$users = [$user];
$agents = [];
if ($user->getChildren()->count()) {
$users = array_merge($users, $user->getChildren()->toArray());
$agents = $user->getChildren();
}
$query = $this->userManager->getListingsByLocation($users, $location);
if (empty($query->getQuery()->getScalarResult()) && $location) {
return $this->redirectToRoute('aqarmap_user_listings', [
'id' => $user->getId(),
'location' => $location->getParent() ? $location->getParent()->getSlug() : null,
], Response::HTTP_MOVED_PERMANENTLY);
}
if (!\in_array($request->get('sort'), ['l.publishedAt', 'l.price', 'l.area'])) {
$request->query->set('sort', 'l.publishedAt');
}
$paginator = $this->paginator;
$listings = $paginator->paginate(
$query,
$pageNumber,
$isTopCustomer ? 6 : 9
);
if ($pageNumber > 1 && empty($listings->getItems())) {
return $this->redirectToFirstPage($request, $user, $location);
}
$userManager = $this->userManager;
$liveListingsCount = $userManager->countLiveListing($user);
if ($isTopCustomer) {
$locationManager = $this->locationManager;
return $this->render('@AqarmapUser/Profile/agent.html.twig', [
'results' => $listings,
'user' => $user,
'servedLocationsPills' => $this
->topCustomerService
->getServedLocations($users, $location, 1),
'isCompanyProfile' => (bool) $user->getChildrenCount(),
'companyAgents' => $agents,
'location' => $location,
'form' => $this->createQuickLeadForm(),
'liveListingsCount' => $liveListingsCount,
'leadsCount' => $user->getClientServedCount(),
'servedLocations' => $locationManager
->buildServingLeveledLocationsArray($users, 1, $request->getLocale()),
'agent' => true,
]);
}
return $this->render('@AqarmapUser/User/index.html.twig', [
'liveListingsCount' => $liveListingsCount,
'entity' => $listings,
'user' => $user,
'agent' => $user,
]);
}
/**
* Unset User Logo.
*/
#[Route(path: '/logo/unset', name: 'aqarmap_user_logo_unset')]
#[\Symfony\Component\Security\Http\Attribute\IsGranted(attribute: 'ROLE_USER')]
public function unsetLogo(): RedirectResponse
{
/** @var User $user */
$user = $this->getUser();
$user->setLogo(null);
$user->setIsValidLogo(false);
$response = new Response();
$response->headers->clearCookie('hide_logo_request');
$response->sendHeaders();
$userManager = $this->fosUserManager;
$userManager->updateUser($user);
$request->getSession()->getFlashBag()->add(
'success',
$this->translator->trans('profile.flash.user_updated')
);
return new RedirectResponse($this->generateUrl('fos_user_profile_edit'));
}
/**
* Quick Registration Action.
*/
#[Route(path: '/', name: 'aqarmap_user_insert', options: ['expose' => true], methods: ['POST'])]
#[Rest\View]
public function post(Request $request)
{
$userManager = $this->fosUserManager;
/** @var User $user */
$user = $userManager->createUser();
$form = $this->createForm(QuickRegistrationFormType::class, $user, [
'method' => 'POST',
'action' => $this->generateUrl('aqarmap_user_insert'),
'validation_groups' => ['simplified'],
'onlyEmail' => true,
]);
$form->handleRequest($request);
// Marking the user as a quick registered
$user->setIsQucikRegistered(true);
$usernameFromEmail = explode('@', $user->getEmail());
$user->setFullName($usernameFromEmail[0]);
$registered = $this->userManager->quickRegister($user, $form, $request, true, false, false, $request->get('registerWithPassword', false));
if (true === $registered) {
return [
'status' => 'ok',
'message' => $this->translator->trans('popup_form.success'),
];
}
return $form;
}
#[Route(path: '/interests/', name: 'aqarmap_my_interests')]
#[\Symfony\Component\Security\Http\Attribute\IsGranted(attribute: 'IS_AUTHENTICATED_REMEMBERED')]
public function myInterests(Request $request)
{
$user = $this->getUser();
$em = $this->entityManager;
// Creating pagination
$paginator = $this->paginator;
$pagination = $paginator->paginate(
$em->getRepository(UserInterest::class)->getUserInterests($user, 20),
$request->query->get('page', 1),
20
);
return [
'interests' => $pagination,
];
}
#[Route(path: '/interests/{id}/pause', requirements: ['id' => '\d+'], name: 'aqarmap_interests_pause', methods: ['GET'])]
#[\Symfony\Component\Security\Http\Attribute\IsGranted(attribute: new \Symfony\Component\ExpressionLanguage\Expression("is_granted('ROLE_ADMIN') or is_granted('ROLE_OWNER', entity)"))]
public function pauseInterest(Request $request, UserInterest $entity): RedirectResponse
{
if (!$entity) {
throw $this->createNotFoundException('Unable to find this Interest.');
}
$em = $this->entityManager;
$entity->setStatus(UserInterestStatus::PAUSED);
// Save Changes
$em->persist($entity);
$em->flush();
// Set success flash message
$request->getSession()->getFlashBag()->add(
'info',
$this->translator->trans('interest.paused_successfully')
);
return $this->redirect($request->headers->get('referer') ?: $this->generateUrl('homepage'));
}
/**
* User Activity.
*/
#[Route(path: '/activity/{step}', name: 'user_activity', options: ['expose' => true])]
#[Route(path: '/{userKey}/activity/{step}', name: 'user_activity_share', options: ['expose' => true])]
#[\Symfony\Component\Security\Http\Attribute\IsGranted(attribute: 'IS_AUTHENTICATED_REMEMBERED')]
public function activity(Request $request): Response
{
$request->query->add([
'user_key' => $request->attributes->get('userKey'),
'limit' => 1,
]);
if ($request->attributes->get('userKey')) {
$favourite = $this->favouriteService->getUserFavourite($request)->getResult();
}
return $this->render('@AqarmapUser/User/activity.html.twig', [
'favourite' => current($favourite ?? []),
'featureToggle' => $this->userActivityService->getFeatureToggles(),
]);
}
/**
* User Inbox.
*/
#[Route(path: '/inbox/', name: 'user_inbox', options: ['expose' => true])]
#[\Symfony\Component\Security\Http\Attribute\IsGranted(attribute: 'IS_AUTHENTICATED_REMEMBERED')]
public function inbox(): Response
{
$entityManager = $this->managerRegistry;
$featureToggleManager = $this->featureToggleManager;
return $this->render('@AqarmapUser/User/inbox.html.twig', [
'location' => $entityManager->getRepository(Location::class)->getFirstRoot(),
'propertyType' => $entityManager->getRepository(PropertyType::class)->getFirstRoot(),
'section' => $entityManager->getRepository(Section::class)->getFirstSection(),
'featureToggle' => [
'web.whats.app.chat' => $featureToggleManager->isEnabled('web.whats.app.chat'),
],
]);
}
/**
* User Message.
*/
#[Route(path: '/messages/{id}', name: 'user_message', options: ['expose' => true])]
#[\Symfony\Component\Security\Http\Attribute\IsGranted(attribute: 'IS_AUTHENTICATED_REMEMBERED')]
public function messages(): Response
{
$featureToggleManager = $this->featureToggleManager;
return $this->render('@AqarmapUser/User/inbox.html.twig', [
'featureToggle' => [
'web.whats.app.chat' => $featureToggleManager->isEnabled('web.whats.app.chat'),
],
]);
}
public function createQuickLeadForm(): FormInterface
{
return $this->createForm(
QuickLeadType::class,
null,
[
'action' => $this->generateUrl('add_quick_lead'),
'method' => 'POST',
]
);
}
#[Route(path: '/interests/unsubscribe/{locationId}', name: 'aqarmap_poke_notifier_unsubscribe', methods: ['GET'])]
public function unsubscribeLocationNotifier(Request $request, int $locationId): RedirectResponse
{
$token = $request->query->get('token');
$subscriptionService = $this->notifierSubscriptionService;
$subscriptionService->unsubscribeLocation($locationId, $token);
return $this->redirectToRoute('homepage');
}
#[Route(path: '/interests/unsubscribe', name: 'aqarmap_all_poke_notifiers_unsubscribe', methods: ['GET'])]
public function unsubscribeAllNotifiers(Request $request): RedirectResponse
{
$token = $request->query->get('token');
$subscriptionService = $this->notifierSubscriptionService;
$subscriptionService->unsubscribeAll($token);
return $this->redirectToRoute('homepage');
}
/**
* Google login action.
*
* @return RedirectResponse
*/
#[Route(path: '/google/login', name: 'user_google_login')]
public function googleLogin(Request $request)
{
$isGoogleToggleEnabled = $this->featureToggleManager->isEnabled('web.google.onetab');
if (!$isGoogleToggleEnabled) {
return $this->redirectToRoute('homepage');
}
$client = $this->googleUserManager->createGoogleClient();
$code = $request->query->get('code');
if (!$code) {
$referer = $request->headers->get('referer');
$this->get('session')->set('referer_url', $referer);
return $this->redirect($client->createAuthUrl());
}
try {
$refererPage = $this->get('session')->get('referer_url') ?: $this->generateUrl('homepage');
$userData = $this->googleUserManager->getUserDataFromToken($client, $code);
} catch (\Exception) {
$this->addFlash('danger', $this->translator->trans('user.something_went_wrong'));
return $this->redirect($refererPage);
}
$userHasNoRetrievedData = (!$userData->getId() && !$userData->getName() && !$userData->getEmail());
if ($userHasNoRetrievedData) {
$this->addFlash('danger', $this->translator->trans('user.something_went_wrong'));
return $this->redirect($refererPage);
}
$user = $this->googleUserManager->createOrUpdateUser($userData);
$data = [];
$data['token'] = $this->googleUserManager->createUserAccessToken($request->request->get('aqarmap_teleport_client_id'), $user);
$data['referer'] = $refererPage;
$userToken = $this->userAuthenticationServiceV3->generateToken($user, false);
$this->usageTrackingTokenStorage->setToken($userToken);
$this->get('session')->set('_security_main', serialize($userToken));
return $this->render('@AqarmapUser/User/google_call_back.html.twig', ['data' => $data]);
}
private function redirectToFirstPage(Request $request, User $user, ?Location $location = null): RedirectResponse
{
$request->query->remove('page');
return $this->redirectToRoute('aqarmap_user_listings', [
'id' => $user->getId(),
'location' => $location ? $location->getSlug() : null,
], Response::HTTP_MOVED_PERMANENTLY);
}
}