src/Controller/SecurityController.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AccommodationType;
  4. use App\Entity\Blog;
  5. use App\Entity\Bookings;
  6. use App\Entity\DiscountCode;
  7. use App\Entity\EmailTracing;
  8. use App\Entity\Media;
  9. use App\Entity\Property;
  10. use App\Entity\User;
  11. use App\Security\LoginFormAuthenticator;
  12. use App\Service\GlobalFunctions;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  15. use Symfony\Component\Form\Extension\Core\Type\TextType;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  20. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  21. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  22. class SecurityController extends AbstractController
  23. {
  24.     public function __construct(\Swift_Mailer $mailer)
  25.     {
  26.         $this->mailer $mailer;
  27.     }
  28.     /**
  29.      * @Route("/login", name="app_login")
  30.      */
  31.     public function login(AuthenticationUtils $authenticationUtils): Response
  32.     {
  33.         // get the login error if there is one
  34.         $error $authenticationUtils->getLastAuthenticationError();
  35.         // last username entered by the user
  36.         $lastUsername $authenticationUtils->getLastUsername();
  37.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  38.     }
  39.     public function changeProfilePic()
  40.     {
  41.         $user $this->get('security.token_storage')->getToken()->getUser();
  42.         $Photo $this->getDoctrine()->getRepository(Media::class)->findOneBy([
  43.                 'UserId' => $user,
  44.         ]);
  45.         if (!$Photo) {
  46.         }
  47.         $NewPhoto = new Media();
  48.         $entityManager $this->getDoctrine()->getManager();
  49.         $form $this->createFormBuilder($NewPhoto)
  50.             ->add('documentFile'VichImageType::class)
  51.             ->add('Description'TextType::class, ['label' => 'Caption'])
  52.             ->add('save'SubmitType::class, ['label' => 'Upload'])
  53.             ->getForm();
  54.         $form->handleRequest($request);
  55.         if ($form->isSubmitted() && $form->isValid()) {
  56.             // $form->getData() holds the submitted values
  57.             // but, the original `$task` variable has also been updated
  58.             $NewPhoto $form->getData();
  59.             $NewPhoto->setPropertyCode($listing_code);
  60.             $entityManager->persist($NewPhoto);
  61.             $entityManager->flush();
  62.         }
  63.         return $this->render('security/profilepic.html.twig', [
  64.             'profileform' => $form->createView(),
  65.         ]);
  66.     }
  67.     public function stripeTokenise($stripe_token)
  68.     {
  69.         $em $this->getDoctrine()->getManager();
  70.         \Stripe\Stripe::setApiKey(getenv('stripe_secret_key'));
  71.         $User $this->get('security.token_storage')->getToken()->getUser();
  72.         if (null !== $User->getStripeCustomerToken()) {
  73.             $updateCustomer = \Stripe\Customer::update(
  74.                 $User->getStripeCustomerToken(),
  75.                 ['source' => $stripe_token]
  76.             );
  77.         } else {
  78.             $newCustomer = \Stripe\Customer::create([
  79.                 'name' => $User->getFirstName().' '.$User->getLastName(),
  80.                 'email' => $User->getEmail(),
  81.                 'source' => $stripe_token,
  82.             ]);
  83.             $User->setStripeCustomerToken($newCustomer->id);
  84.             $em->persist($User);
  85.             $em->flush();
  86.         }
  87.         return new Response('success');
  88.     }
  89.     public function updateSavedCard()
  90.     {
  91.         $user $this->get('security.token_storage')->getToken()->getUser();
  92.         $StripeCustomerToken $user->getStripeCustomerToken();
  93.         if (null == $StripeCustomerToken) {
  94.             $StripeDetail '<h4>You do not have a card saved on file</h4>';
  95.         } else {
  96.             \Stripe\Stripe::setApiKey(getenv('stripe_secret_key'));
  97.             $StripeCustomer = \Stripe\Customer::retrieve($StripeCustomerToken);
  98.             if (array_key_exists(0$StripeCustomer->sources->data)) {
  99.                 $StripeCardToken $StripeCustomer->sources->data[0];
  100.                 $StripeDetail '<h4>'.$StripeCardToken->brand.' Card ending ****'.$StripeCardToken->last4.'</h4>Expires '.$StripeCardToken->exp_month.'/'.$StripeCardToken->exp_year;
  101.             } else {
  102.                 $StripeDetail '<h4>You do not have a card saved on file</h4>';
  103.             }
  104.         }
  105.         return $this->render('security/savedcard.html.twig', [
  106.             'stripe_detail' => $StripeDetail,
  107.                 'stripe_public_key' => getenv('stripe_public_key'),
  108.         ]);
  109.     }
  110.     public function createGuest(GuardAuthenticatorHandler $guardHandlerRequest $requestLoginFormAuthenticator $authenticatorUserPasswordEncoderInterface $passwordEncoder)
  111.     {
  112.         $FirstName $request->request->get('FirstName');
  113.         $LastName $request->request->get('LastName');
  114.         $EmailAddress $request->request->get('EmailAddress');
  115.         $MobileNumber $request->request->get('MobileNumber');
  116.         if (null !== $request->request->get('Location')) {
  117.             $Location $request->request->get('Location');
  118.             $Gender $request->request->get('Gender');
  119.             $NewPassword $request->request->get('NewPassword');
  120.         }
  121.         $entityManager $this->getDoctrine()->getManager();
  122.         $GetUser $this->getDoctrine()->getRepository(User::class)->findOneBy(['email' => $EmailAddress]);
  123.         if ($GetUser) {
  124.             return new Response('user_exists');
  125.         } else {
  126.             $User = new User();
  127.             $User->setUsername($EmailAddress);
  128.             $User->setUsernameCanonical($EmailAddress);
  129.             $User->setEmail($EmailAddress);
  130.             $User->setEmailCanonical($EmailAddress);
  131.             $User->setEnabled(1);
  132.             $User->setTermsAccepted(1);
  133.             $User->setRoles(['ROLE_USER']);
  134.             $User->setFirstName($FirstName);
  135.             $User->setLastName($LastName);
  136.             $User->setMobilePh($MobileNumber);
  137.             $User->setPassword($passwordEncoder->encodePassword($User$NewPassword));
  138.             $entityManager->persist($User);
  139.             $entityManager->flush();
  140.             $doLogin $guardHandler->authenticateUserAndHandleSuccess(
  141.                 $User,
  142.                 $request,
  143.                 $authenticator,
  144.                 'main' // firewall name in security.yaml
  145.             );
  146.             return new Response('success');
  147.         }
  148.     }
  149.     public function interimDashboard(GlobalFunctions $GlobalFn)
  150.     {
  151.         /** @var User|null $user - Resolves ->getId() as it doesn't know it's an entity */
  152.         $user $this->getUser();
  153.         if (!$user) {
  154.             return $this->redirectToRoute('app_login');
  155.         }
  156.         $user_id $user->getId();
  157.         $getTrips $this->getDoctrine()
  158.         ->getRepository(Bookings::class)->findBy(
  159.             ['HolidaymakerId' => $user_id,
  160.              'Status' => ['Confirmed''Awaiting Acceptance'], ]
  161.         );
  162.         $getAccommTypes $this->getDoctrine()
  163.         ->getRepository(AccommodationType::class)->findBy(
  164.             ['LandownerId' => $user_id,
  165.             'Enabled' => true, ]
  166.         );
  167.         $AccommRoomCodes = [];
  168.         foreach ($getAccommTypes as $thisAccomm) {
  169.             $AccommRoomCodes[] = $thisAccomm->getRoomCode();
  170.         }
  171.         $getAllTrips $this->getDoctrine()
  172.         ->getRepository(Bookings::class)->findBy(
  173.             ['RoomCode' => $AccommRoomCodes]
  174.         );
  175.         $TripInfo = [];
  176.         $RoomInfo = [];
  177.         $PropertyInfo = [];
  178.         foreach ($getTrips as $ThisTrip) {
  179.             $TripInfo[$ThisTrip->getId()] = $ThisTrip;
  180.             $ThisRoomInfo $this->getDoctrine()
  181.             ->getRepository(AccommodationType::class)->findOneBy(
  182.                 ['RoomCode' => $ThisTrip->getRoomCode()]
  183.             );
  184.             $ThisPropertyInfo $this->getDoctrine()
  185.             ->getRepository(Property::class)->findOneBy(
  186.                 ['ListingCode' => $ThisRoomInfo->getPropertyCode()]
  187.             );
  188.             $RoomInfo[$ThisTrip->getId()] = $ThisRoomInfo;
  189.             $PropertyInfo[$ThisTrip->getId()] = $ThisPropertyInfo;
  190.         }
  191.         $AllTripInfo = [];
  192.         $AllRoomInfo = [];
  193.         $AllPropertyInfo = [];
  194.         foreach ($getAllTrips as $ThisTrip) {
  195.             $AllTripInfo[$ThisTrip->getId()] = $ThisTrip;
  196.             $ThisRoomInfo $this->getDoctrine()
  197.             ->getRepository(AccommodationType::class)->findOneBy(
  198.                 ['RoomCode' => $ThisTrip->getRoomCode()]
  199.             );
  200.             $ThisPropertyInfo $this->getDoctrine()
  201.             ->getRepository(Property::class)->findOneBy(
  202.                 ['ListingCode' => $ThisRoomInfo->getPropertyCode()]
  203.             );
  204.             $AllRoomInfo[$ThisTrip->getId()] = $ThisRoomInfo;
  205.             $AllPropertyInfo[$ThisTrip->getId()] = $ThisPropertyInfo;
  206.         }
  207.         $two_weeks = new \DateTime('-2 weeks');
  208.         $MyListings = []; // @phpstan-ignore-next-line
  209.         $getListings $this->getDoctrine()
  210.             ->getRepository(Property::class)
  211.             ->createQueryBuilder('p')
  212.             ->where('p.LandownerId = :user_id')
  213.             // ->andWhere('p.CreatedDate >= :two_weeks  ')
  214.             ->setParameters([
  215.                 'user_id' => $user_id,
  216.                 // 'two_weeks' => $two_weeks
  217.             ])
  218.             ->orderBy('p.ListingStatus''DESC')
  219.             ->getQuery()
  220.             ->getResult();
  221.         foreach ($getListings as $thisListing) {
  222.             $MyListings[] = $thisListing->getListingCode();
  223.         }
  224.         /*$SwiftMailer = new \Swift_Mailer();
  225.         $GlobalFn = new GlobalFunctions($this->getDoctrine()->getManager(), $SwiftMailer);*/
  226.         $PendingBookings $this->getDoctrine()
  227.         ->getRepository(Bookings::class)->findBy(
  228.             ['PropertyCode' => $MyListings,
  229.              'Status' => 'Awaiting Acceptance', ]
  230.         );
  231.         $GetHolidaymakerPending = [];
  232.         $PendingNumNights = [];
  233.         foreach ($PendingBookings as $ThisPendingBooking) {
  234.             $GetHolidaymakerPending[$ThisPendingBooking->getHolidaymakerId()] = $this->getDoctrine()
  235.             ->getRepository(User::class)->find($ThisPendingBooking->getHolidaymakerId());
  236.             $PendingNumNights[$ThisPendingBooking->getHolidaymakerId()] = $GlobalFn->get_booking_info($ThisPendingBooking->getId(), 'number_nights');
  237.         }
  238.         $UpcomingBookings $this->getDoctrine()
  239.         ->getRepository(Bookings::class)->findBy(
  240.             ['RoomCode' => $AccommRoomCodes,
  241.              'Status' => ['Confirmed''Block Out'], ], ['BookingFrom' => 'ASC']
  242.         );
  243.         $GetHolidaymakerUpcoming = [];
  244.         $UpcomingNumNights = [];
  245.         foreach ($UpcomingBookings as $ThisUpcomingBooking) {
  246.             $GetHolidaymakerUpcoming[$ThisUpcomingBooking->getHolidaymakerId()] = $this->getDoctrine()
  247.             ->getRepository(User::class)->find($ThisUpcomingBooking->getHolidaymakerId());
  248.             $UpcomingNumNights[$ThisUpcomingBooking->getHolidaymakerId()] = $GlobalFn->get_booking_info($ThisUpcomingBooking->getId(), 'number_nights');
  249.         }
  250.         $ProfilePicture $GlobalFn->user_photo($user->getId());
  251.         $LandownerBlog $this->getDoctrine()->getRepository(Blog::class)->findBy(['Tag' => 'landowner'], ['id' => 'DESC']);
  252.         return $this->render('security/interimdashboard.html.twig', [
  253.             'user' => $user,
  254.             'user_id' => $user_id,
  255.             'listings' => $getListings,
  256.             'accomm_types' => $getAccommTypes,
  257.             'trips' => $getTrips,
  258.             'trip_info' => $TripInfo,
  259.             'room_info' => $RoomInfo,
  260.             'all_room_info' => $AllRoomInfo,
  261.             'all_trip_info' => $AllTripInfo,
  262.             'all_property_info' => $AllPropertyInfo,
  263.             'property_info' => $PropertyInfo,
  264.             'pending_bookings' => $PendingBookings,
  265.             'upcoming_bookings' => $UpcomingBookings,
  266.             'holidaymaker_pending' => $GetHolidaymakerPending,
  267.             'holidaymaker_upcoming' => $GetHolidaymakerUpcoming,
  268.             'num_nights_pending' => $PendingNumNights,
  269.             'profile_picture' => $ProfilePicture,
  270.             'num_nights_upcoming' => $UpcomingNumNights,
  271.             'landowner_blog' => $LandownerBlog,
  272.         ]);
  273.     }
  274.     public function editProfile(GlobalFunctions $GlobalFnRequest $request)
  275.     {
  276.         $user $this->getUser();
  277.         $entityManager $this->getDoctrine()->getManager();
  278.         $ProfilePicture $GlobalFn->user_photo($user->getId());
  279.         $form $this->createFormBuilder($user)
  280.             ->add('FirstName')
  281.             ->add('LastName')
  282.             ->add('LandlinePh')
  283.             ->add('MobilePh')
  284.             ->add('AltEmail')
  285.             ->add('save'SubmitType::class, ['label' => 'Save Details'])
  286.             ->getForm();
  287.         $form->handleRequest($request);
  288.         if ($form->isSubmitted() && $form->isValid()) {
  289.             $user $form->getData();
  290.             $entityManager->persist($user);
  291.             $entityManager->flush();
  292.             return $this->render('security/profileedit.html.twig', [
  293.                 'form' => $form->createView(),
  294.                 'profile_picture' => $ProfilePicture,
  295.                 'form_updated' => true,
  296.             ]);
  297.         } else {
  298.             return $this->render('security/profileedit.html.twig', [
  299.                 'form' => $form->createView(),
  300.                 'profile_picture' => $ProfilePicture,
  301.                 'form_updated' => false,
  302.             ]);
  303.         }
  304.     }
  305.     public function newDashboard(GlobalFunctions $GlobalFn)
  306.     {
  307.         $user $this->get('security.token_storage')->getToken()->getUser();
  308.         $ProfilePicture $GlobalFn->user_photo($user->getId());
  309.         return $this->render('security/newdashboard.html.twig', [
  310.             'user' => $user,
  311.             'profile_picture' => $ProfilePicture,
  312.         ]);
  313.     }
  314.     public function guestDashboard()
  315.     {
  316.         $user $this->get('security.token_storage')->getToken()->getUser();
  317.         return $this->render('security/newdashboard.html.twig', [
  318.             'user' => $user,
  319.         ]);
  320.     }
  321.     /**
  322.      * @Route("/newsletterregisterendpoint", name="newsletterregisterendpoint")
  323.      */
  324.     public function newsletterSubscribe(Request $requestGlobalFunctions $fn)
  325.     {
  326.         $email $request->request->get('email');
  327.         $first_name $request->request->get('first_name');
  328.         $sg = new \App\Classes\SendGrid();
  329.         $search_request json_decode('{
  330.             "list_id": 4302212,
  331.             "conditions": [
  332.                 {"and_or":"","field":"email","value":"'.$email.'","operator":"eq"}
  333.             ]
  334.             } ');
  335.         $response $sg->client->contactdb()->recipients()->search()->post($search_request);
  336.         $response_json json_decode($response->body());
  337.         if (isset($response_json->recipient_count) && $response_json->recipient_count 0) {
  338.             if ($request->isXmlHttpRequest()) {
  339.                 return new Response('already_listed');
  340.             }
  341.             $referer $request->headers->get('referer') ?? $this->generateUrl('newsletter');
  342.             return $this->redirect($referer.'?error_message=already_listed');
  343.         } else {
  344.             $request_body json_decode('[
  345.                 {
  346.                 "email": "'.$email.'",
  347.                 "first_name": "'.$first_name.'"
  348.                 }
  349.             ]');
  350.             $response $sg->client->contactdb()->recipients()->post($request_body);
  351.             $response_json json_decode($response->body());
  352.             $recipient_id $response_json->persisted_recipients[0];
  353.             $request_body json_decode('[
  354.                 "'.$recipient_id.'"
  355.             ]');
  356.             $list_id 4302212;
  357.             $response $sg->client->contactdb()->lists()->_($list_id)->recipients()->post($request_body);
  358.             $this->get('session')->set('newsletter_popup_dismissed''dismissed');
  359.             // ///////// Send out emails
  360.             // Create Discount Code
  361.             $entityManager $this->getDoctrine()->getManager();
  362.             /*$Code = "WELCOME20_".substr(strtoupper($first_name),0,20).rand(1000,9999);
  363.             $DateExpiry = new \DateTime(date("Y-m-d",strtotime("+30 days")));
  364.             $DiscountCode = new DiscountCode();
  365.             $DiscountCode->setCode($Code);
  366.             $DiscountCode->setReservedUses(0);
  367.             $DiscountCode->setAllowOnlyMinNights(1);
  368.             $DiscountCode->setAllowOnlyMinSpend(0);
  369.             $DiscountCode->setValidFrom(new \DateTime());
  370.             $DiscountCode->setValidTo($DateExpiry);
  371.             $DiscountCode->setDiscountAmount("20");
  372.             $DiscountCode->setEmail($email);
  373.             $entityManager->persist($DiscountCode);
  374.             $entityManager->flush();*/
  375.             $fn->send_template_email($email'join_tribe_welcome_email', [
  376.                 'first_name' => $first_name,
  377.             ]);
  378.             if ($request->isXmlHttpRequest()) {
  379.                 return new Response('success');
  380.             }
  381.             $referer $request->headers->get('referer') ?? $this->generateUrl('newsletter');
  382.             return $this->redirect($referer.'?success');
  383.         }
  384.     }
  385.     /**
  386.      * @Route("/newsletterstoppopup", name="newsletterstoppopup")
  387.      */
  388.     public function newsletterStopPopup(Request $request)
  389.     {
  390.         $this->get('session')->set('newsletter_popup_dismissed''dismissed');
  391.         return new Response('dismissed');
  392.     }
  393.     /**
  394.      * @Route("/getnewsletterstatus", name="getnewsletterstatus")
  395.      */
  396.     public function getnewsletterstatus(Request $request)
  397.     {
  398.         $status $this->get('session')->get('newsletter_popup_dismissed');
  399.         if ('dismissed' == $status) {
  400.             return new Response('dismissed');
  401.         } else {
  402.             return new Response('show');
  403.         }
  404.     }
  405.     /**
  406.      * @Route("/exitintentserved", name="exitintentserved")
  407.      */
  408.     public function exitintentserved(Request $request)
  409.     {
  410.         $this->get('session')->set('exitintent_popup_dismissed''dismissed');
  411.         return new Response('dismissed');
  412.     }
  413.     /**
  414.      * @Route("/sendexitintent", name="sendexitintent")
  415.      */
  416.     public function sendexitintent(Request $request)
  417.     {
  418.         $email_address $request->request->get('email_address');
  419.         $first_name $request->request->get('first_name');
  420.         $location $request->request->get('location');
  421.         $looking_for $request->request->get('looking_for');
  422.         $message = (new \Swift_Message('Need a hand request - '.$first_name))
  423.             ->setFrom('support@otbt.co.nz')
  424.             ->setTo('info@otbt.co.nz')
  425.             ->setBody(
  426.                 'Hi there, a need a hand request has been received.<br><br>Requested By: '.$first_name.'<br>Email: '.$email_address.'<br><br>Location: '.$location.'<br><br>Looking For:<br>'.$looking_for.'<br><br>OTBT System',
  427.                 'text/html'
  428.             );
  429.         $this->mailer->send($message);
  430.         $this->get('session')->set('exitintent_popup_dismissed''dismissed');
  431.         return new Response('success');
  432.     }
  433.     /**
  434.      * @Route("/countemailopen/{id}", name="count_email_open")
  435.      */
  436.     public function count_email_open(EmailTracing $email)
  437.     {
  438.         $newCount $email->getOpens() + 1;
  439.         $email->setOpens($newCount);
  440.         $entityManager $this->getDoctrine()->getManager();
  441.         $entityManager->persist($email);
  442.         $entityManager->flush();
  443.         return new Response('success');
  444.     }
  445. }