src/Social/FrontendBundle/Controller/AccountController.php line 65

Open in your IDE?
  1. <?php
  2. namespace Social\FrontendBundle\Controller;
  3. use DateTime;
  4. use Sentry\ClientInterface;
  5. use Doctrine\DBAL\DBALException;
  6. use Social\CreditsBundle\Entity\CreditActionsEntity;
  7. use Social\CreditsBundle\Entity\CreditUserHistoryEntity;
  8. use Social\FrontendBundle\Entity\AlertsUserToast;
  9. use Social\FrontendBundle\Entity\CentralPaySFConfirmationPayment;
  10. use Social\FrontendBundle\Entity\Payment;
  11. use Social\FrontendBundle\Entity\SwipeHistory;
  12. use Social\FrontendBundle\Entity\VerotelConfirmationPayment;
  13. use Social\FrontendBundle\Service\UserActionManager;
  14. use Social\InternalBundle\Entity\BootProfile;
  15. use Social\InternalBundle\Entity\PackagesList;
  16. use Social\InternalBundle\Entity\UserBoostProfileHistory;
  17. use Social\UserBundle\Form\UserType;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use Doctrine\ORM\OptimisticLockException;
  20. use Exception;
  21. use GuzzleHttp\Client;
  22. use Egulias\EmailValidator\Validation\RFCValidation;
  23. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  24. use Symfony\Component\Security\Core\User\UserInterface;
  25. use Social\InternalBundle\Entity\TrafficPoll\Conversions;
  26. use Social\InternalBundle\Entity\TrafficPool;
  27. use Social\InternalBundle\Entity\UserDeletionQueue;
  28. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  29. use Social\InternalBundle\Service\PaymentMethods\CentralPay\HookUtility;
  30. use Social\UserBundle\Entity\User;
  31. use Social\UserBundle\Entity\UserComponents\UserSignupPollData;
  32. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  33. use Symfony\Component\HttpFoundation\Cookie;
  34. use Symfony\Component\HttpFoundation\JsonResponse;
  35. use Symfony\Component\HttpFoundation\RedirectResponse;
  36. use Symfony\Component\HttpFoundation\Request;
  37. use Symfony\Component\HttpFoundation\Response;
  38. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  39. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  40. use Symfony\Component\Security\Core\Role\SwitchUserRole;
  41. use Symfony\Component\Security\Http\Event\SwitchUserEvent;
  42. use Symfony\Component\Security\Http\SecurityEvents;
  43. use Symfony\Component\Validator\Constraints\File;
  44. use Egulias\EmailValidator\EmailValidator;
  45. use Social\InternalBundle\Entity\Language;
  46. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  47. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  48. /**
  49.  * Class AccountController
  50.  *
  51.  * @package Social\FrontendBundle\Controller
  52.  */
  53. class AccountController extends Controller
  54. {
  55.     /**
  56.      * @param Request                $request
  57.      * @param EntityManagerInterface $entityManager
  58.      *
  59.      * @return Response
  60.      * @throws OptimisticLockException
  61.      */
  62.     public function accountAction(Request $requestEntityManagerInterface $entityManager): Response
  63.     {
  64.         $em $entityManager;
  65.         /** @var User $currentUser */
  66.         $currentUser $this->getUser();
  67.         $form null;
  68.         $goInTrafficPollFlag false;
  69.         
  70.         if ( !$currentUser ) {
  71.             $form $this->createForm(
  72.                 UserType::class,
  73.                 null,
  74.                 [ 'include_birthday' => true'include_agree' => true ]
  75.             );
  76.             $form $form->createView();
  77.             $goInTrafficPollFlag true;
  78.             
  79.             /** @var User $user */
  80.             $user $this->get('social.accessibility_manager')->getViewedUser();
  81.             if ( !$user ) {
  82.                 throw $this->createNotFoundException(
  83.                     sprintf(
  84.                         'There is no user with the "%s"',
  85.                         $request->get('username')
  86.                     )
  87.                 );
  88.             }
  89.         } else {
  90.             if ( $this->getUser() && $this->getUser() instanceof User) {
  91.                 $user $this->getUser()->getViewedUser();
  92.             } else {
  93.                 $user null;
  94.             }
  95.         }
  96.         // Check if current user has location
  97.         if ( $currentUser && $currentUser instanceof User && $currentUser->getIsFake() != true && $currentUser->getOwner() == null ) {
  98.             if ( $currentUser->getNewLocation() == null ) {
  99.                 $userIP $request->getClientIp();
  100.                 $locale $request->getLocale();
  101.                 
  102.                 $userLocationTrack $this->get('social_internal.ip_track_manager')->getLocationForIp($userIP);
  103.                 $userLocation $this->get('social_internal.ip_track_manager')->getLocationFromDBForUserObject(
  104.                     $userLocationTrack,
  105.                     $locale
  106.                 );
  107.                 
  108.                 if ( $userLocation != null ) {
  109.                     if ( is_array($userLocation) ) {
  110.                         $beforeLocation $user->getNewLocation();
  111.                         if ( $beforeLocation == null ) {
  112.                             try {
  113.                                 /** @var UserSignupPollData $userPollSignUp */
  114.                                 $userPollSignUp $this->getDoctrine()->getRepository(UserSignupPollData::class)
  115.                                                        ->findOneBy([ 'userReference' => $user ]);
  116.                                 
  117.                                 if ( $userPollSignUp ) {
  118.                                     if ( $userPollSignUp->getPollReference() ) {
  119.                                         /** @var TrafficPool $trafficPoll */
  120.                                         $trafficPoll $userPollSignUp->getPollReference();
  121.                                         $conversions $trafficPoll->getConversions();
  122.                                         
  123.                                         if ($conversions) {
  124.                                             /** @var Conversions $conversion */
  125.                                             foreach ($conversions as $conversion) {
  126.                                                 if ($conversion->getActive()) {
  127.                                                     $client = new Client();
  128.                                                     $random time() + random_int(19999);
  129.                                                     $url $conversion->getUrl();
  130.                                                     $url .= '&cb='.$random;
  131.                                                     $url .= '&cti='.$user->getId().'-'.$trafficPoll->getCode();
  132.                                                     $this->get('sentry.client')->captureMessage($url);
  133.                                                     $response $client->get($url);
  134.                                                     $this->get('sentry.client')->captureMessage($response->getStatusCode());
  135.                                                 }
  136.                                             }
  137.                                         }
  138.                                     }
  139.                                 }
  140.                             } catch ( Exception $exception ) {
  141.                                 $this->get('sentry.client')->captureException($exception);
  142.                             }
  143.                         }
  144.                     }
  145.                 }
  146.                 
  147.                 $em->persist($user);
  148.                 $em->flush();
  149.             }
  150.         }
  151.         
  152.         if ( $currentUser instanceof UserInterface ) {
  153.             if ( $user && $user->getId() != $currentUser->getId() ) {
  154.                 if ( !$this->get('social.accessibility_manager')->canUserViewProfile($currentUser$user) ) {
  155.                     throw new UsernameNotFoundException();
  156.                 }
  157.                 $this->get('social.profile_view_manager')->visitProfile($currentUser$user);
  158.                 $this->get('social.alert_manager')->createAlertViewedProfile($currentUser$user);
  159.                 if ($request->get('isSwiped') && $request->get('isSwiped') == 1) {
  160.                     $existSwipeHistory $em->getRepository(SwipeHistory::class)->findOneBy(['toUser' => $user'fromUser' => $currentUser'event' => SwipeHistory::EVENT_PROFILE_VIEWED]);
  161.                     if (!$existSwipeHistory) {
  162.                         $swipeHistory = new SwipeHistory();
  163.                         $swipeHistory->setEvent(SwipeHistory::EVENT_PROFILE_VIEWED);
  164.                         $swipeHistory->setFromUser($currentUser);
  165.                         $swipeHistory->setToUser($user);
  166.                         $em->persist($swipeHistory);
  167.                         $em->flush();
  168.                     }
  169.                 }
  170.             }
  171.         }
  172.         
  173.         $response $this->render(
  174.             'SocialFrontendBundle:Account:account.html.twig',
  175.             [ 'user' => $user'form' => $form ]
  176.         );
  177.         
  178.         if ( $goInTrafficPollFlag ) {
  179.             $trafficPollIncomeCode $request->get('upi');
  180.             
  181.             if ($request->get('upi')) {
  182.                 $singleTraffic $entityManager->getRepository(TrafficPool::class)->findOneBy(['code' => $request->get('upi')]);
  183.                 if ($singleTraffic) {
  184.                     if ( $singleTraffic->getPollType() == TrafficPool::POLL_TYPE_USER_PAGE && $singleTraffic->getCode() == $trafficPollIncomeCode ) {
  185.                         $urlParams $singleTraffic->getUrlParameters();
  186.                         foreach ( $urlParams as $single ) {
  187.                             $value $request->get($single->getKeyValue(), null);
  188.                             if ( $value != null ) {
  189.                                 $cookie = new Cookie(
  190.                                     'tfpr['.$single->getKeyValue().']'$value0'/'nullfalse,
  191.                                     false
  192.                                 );
  193.                                 $response->headers->setCookie($cookie);
  194.                             }
  195.                         }
  196.                         $cookie = new Cookie('tfpr[pollId]'$singleTraffic->getId(), 0'/'nullfalsefalse);
  197.                         $response->headers->setCookie($cookie);
  198.                     }
  199.                 }
  200.             }
  201.         }
  202.         return $response;
  203.     }
  204.     public function triggerNotificationAction(EntityManagerInterface $entityManager)
  205.     {
  206.         try {
  207.             $user $this->getUser();
  208.             if ($user) {
  209.                 $bubbleAlerts $entityManager->getRepository('SocialFrontendBundle:AlertsUserToast')->getUserAlerts($user4);
  210.                 $pusher $this->container->get('social.pusher_initializer')->initialize();
  211.                 $templating $this->container->get('templating');
  212.                 foreach ($bubbleAlerts as $bubbleAlert) {
  213.                     $date $bubbleAlert->getCreatedAt();
  214.                     $dateTime = new \DateTime($date->format('Y-m-d H:i:s'), new \DateTimeZone('Europe/Bucharest'));
  215.                     $user1 $bubbleAlert->getFromUser();
  216.                     $user2 $bubbleAlert->getToUser();
  217.                     $visit $bubbleAlert->getType() == AlertsUserToast::ALERT_TYPE_PROFILE_VIEW;
  218.                     $url $this->getBubbleUrl($bubbleAlert->getType(), $bubbleAlert);
  219.                     $action AlertsUserToast::getAlertLabel($bubbleAlert->getType());
  220.                     $type AlertsUserToast::getAlertLabel($bubbleAlert->getType());
  221.                     $message $bubbleAlert->getMessage();
  222.                     if ($bubbleAlert->getType() == AlertsUserToast::ALERT_TYPE_PROFILE_VIEW) {
  223.                         $message str_replace($user1->getUsername(), '<a class="blurry-text">' $user1->getUsername() . '</a>'$message);
  224.                     }
  225.                     $action_key $bubbleAlert->getType();
  226.                     $pusher->trigger(
  227.                         'bubble-notifications-' $user2->getId(),
  228.                         'payload',
  229.                         [
  230.                             'username' => $user1->getUsername(),
  231.                             'profile_picture' => $templating->render(
  232.                                 'SocialFrontendBundle::user_image.html.twig',
  233.                                 ['user' => $user1'visit' => $visit]
  234.                             ),
  235.                             'url' => $url,
  236.                             'to_user' => $user2->getUsername(),
  237.                             'picture' => '<i class="fas fa-eye"></i>',
  238.                             'action' => $action,
  239.                             'type' => $type,
  240.                             'message' => $message,
  241.                             'time' => $date->format('Y-m-d H:i:s'),
  242.                             'timestamp' => $dateTime->getTimestamp(),
  243.                             'action_key' => $action_key,
  244.                             'alert_notification_id' => $bubbleAlert->getId()
  245.                         ]
  246.                     );
  247.                     $bubbleAlert->setIsUserOnline(true);
  248.                     $bubbleAlert->setIsSent(true);
  249.                     $entityManager->persist($bubbleAlert);
  250.                     $entityManager->flush();
  251.                     sleep(2);
  252.                 }
  253.             }
  254.             return new JsonResponse(['error' => false]);
  255.         } catch (Exception $exception) {
  256.             return new JsonResponse(['error' => true]);
  257.         }
  258.     }
  259.     public function onBubbleNotificationClickAction(Request $requestEntityManagerInterface $entityManager)
  260.     {
  261.         try {
  262.             $alertId $request->request->get('alertId');
  263.             $alertToast =  $entityManager->getRepository('SocialFrontendBundle:AlertsUserToast')->find($alertId);
  264.             if ($alertToast) {
  265.                 $alertToast->setIsRead(true);
  266.                 $entityManager->persist($alertToast);
  267.                 $entityManager->flush();
  268.             }
  269.             return new JsonResponse('true');
  270.         } catch (Exception $exception) {
  271.             return new JsonResponse(['error' => true]);
  272.         }
  273.     }
  274.     public function removeBubbleNotificationAction(Request $requestEntityManagerInterface $entityManager)
  275.     {
  276.         try {
  277.             $alertId $request->request->get('alertId');
  278.             $alertToast =  $entityManager->getRepository('SocialFrontendBundle:AlertsUserToast')->find($alertId);
  279.             $entityManager->remove($alertToast);
  280.             $entityManager->flush();
  281.             return new JsonResponse('true');
  282.         } catch (Exception $exception) {
  283.             return new JsonResponse(['error' => true]);
  284.         }
  285.     }
  286.     public function onBubbleNotificationClickCloseAction(Request $requestEntityManagerInterface $entityManager)
  287.     {
  288.         try {
  289.             $alertId $request->request->get('alertId');
  290.             $alertToast =  $entityManager->getRepository('SocialFrontendBundle:AlertsUserToast')->find($alertId);
  291.             $alertToast->setIsClosed(true);
  292.             $entityManager->persist($alertToast);
  293.             $entityManager->flush();
  294.             return new JsonResponse('true');
  295.         } catch (Exception $exception) {
  296.             return new JsonResponse(['error' => true]);
  297.         }
  298.     }
  299.     public function getBubbleUrl($type$bubbleAlert)
  300.     {
  301.         $this->router $this->container->get('router');
  302.         $likesComments = [
  303.             AlertsUserToast::ALERT_TYPE_VIDEO_LIKE,
  304.             AlertsUserToast::ALERT_TYPE_VIDEO_COMMENT,
  305.             AlertsUserToast::ALERT_TYPE_PHOTO_COMMENT,
  306.             AlertsUserToast::ALERT_TYPE_PHOTO_LIKE,
  307.         ];
  308.         if (in_array($type$likesComments)) {
  309.             return $this->router->generate(
  310.                     'social_frontend_user_photo',
  311.                     array(
  312.                         'username' => $bubbleAlert->getToUser()->getUsername(),
  313.                         'photo_id' => $bubbleAlert->getToUser()->getImage()->getId(),
  314.                     )
  315.                 ).'#comment-area';
  316.         }
  317.         switch ($type)  {
  318.             case AlertsUserToast::ALERT_TYPE_PROFILE_VIEW:
  319.                 return $this->router->generate('social_account_who_viewed_my_profile');
  320.             case AlertsUserToast::ALERT_TYPE_FRIEND_REQUEST:
  321.                 return $this->router->generate('social_frontend_user_friends', ['username' => $bubbleAlert->getFromUser()->getUsername()]);
  322.             case AlertsUserToast::ALERT_TYPE_FRIEND_APPROVED:
  323.                 return $this->router->generate(
  324.                     'social_frontend_user_about',
  325.                     array('username' => $bubbleAlert->getFromUser()->getUsername()));
  326.             case AlertsUserToast::ALERT_TYPE_MESSAGE:
  327.                 return $this->router->generate('social_frontend_chat_with_friend',
  328.                     array('username' => $bubbleAlert->getFromUser()->getUsername()));
  329.         }
  330.     }
  331.     /**
  332.      * @return Response
  333.      */
  334.     public function detailsAction()
  335.     : Response
  336.     {
  337.         return $this->render('SocialFrontendBundle:Account:details.html.twig');
  338.     }
  339.     
  340.     /**
  341.      * @param Request $request
  342.      *
  343.      * @return Response
  344.      */
  345.     public function updateProfileDetailsAction(Request $request)
  346.     {
  347.         $languages $this->getDoctrine()->getRepository(Language::class)->getByLanguageListArray(
  348.             array_column($this->getParameter('languages'), 'code')
  349.         );
  350.         $form $this->createForm(
  351.             UserType::class,
  352.             $this->getUser(),
  353.             [
  354.                 'destination'       => [ 'step-1''step-3''names' ],
  355.                 'include_birthday'  => true,
  356.                 'email_repeat'      => false,
  357.                 'password_repeat'   => true,
  358.                 'email_disabled'    => true,
  359.                 'username_disabled' => true,
  360.                 'include_language'  => true,
  361.                 'locale'            => $request->getLocale(),
  362.                 'languages'         => array_combine(
  363.                     array_column($languages'name'), 
  364.                     array_column($languages'id')
  365.                 )
  366.             ]
  367.         );
  368.         
  369.         return $this->render(
  370.             'SocialFrontendBundle:Account/Profile:update_profile_details.html.twig',
  371.             [ 'form' => $form->createView() ]
  372.         );
  373.     }
  374.     
  375.     /**
  376.      * @param Request $request
  377.      *
  378.      * @return Response
  379.      */
  380.     public function updateNotificationPreferencesAction(Request $request)
  381.     {
  382.         $form $this->createForm(
  383.             UserType::class,
  384.             $this->getUser(),
  385.             [ 'destination' => [ 'notifications' ], 'locale' => $request->getLocale() ]
  386.         );
  387.         
  388.         return $this->render(
  389.             'SocialFrontendBundle:Account/Profile:update_notification_preferences.html.twig',
  390.             [ 'form' => $form->createView() ]
  391.         );
  392.     }
  393.     
  394.     /**
  395.      * @param Request $request
  396.      *
  397.      * @return Response
  398.      */
  399.     public function updatePersonalizeAccountAction(Request $request)
  400.     {
  401.         $form $this->createForm(
  402.             UserType::class,
  403.             $this->getUser(),
  404.             [ 'destination' => [ 'personalize' ], 'locale' => $request->getLocale() ]
  405.         );
  406.         
  407.         return $this->render(
  408.             'SocialFrontendBundle:Account/Profile:update_personalize_account.html.twig',
  409.             [ 'form' => $form->createView() ]
  410.         );
  411.     }
  412.     
  413.     
  414.     /**
  415.      * @param EntityManagerInterface $entityManager
  416.      *
  417.      * @return Response
  418.      */
  419.     public function displayPaymentHistoryAction(EntityManagerInterface $entityManager)
  420.     : Response {
  421.         $paymentHistory $entityManager->getRepository('SocialFrontendBundle:Payment')->findBy(
  422.             [ 'from_user' => $this->getUser() ],
  423.             [ 'created_at' => 'desc' ]
  424.         );
  425.         
  426.         return $this->render(
  427.             'SocialFrontendBundle:Account/Profile:display_payment_history.html.twig',
  428.             [ 'payment_history' => $paymentHistory ]
  429.         );
  430.     }
  431.     /**
  432.      * @return Response
  433.      */
  434.     public function displaySubscriptionOptionsAction()
  435.     {
  436.         if ( $this->getUser() instanceof User ) {
  437.             $packageName $this->getUser()->getPackageName();
  438.         } else {
  439.             $packageName null;
  440.         }
  441.         return $this->render(
  442.             'SocialFrontendBundle:Account/Profile:display_subscription_options.html.twig', [
  443.                 'package_name' => $packageName,
  444.             ]
  445.         );
  446.     }
  447.     
  448.     /**
  449.      * @param Request $request
  450.      * @param         $type
  451.      *
  452.      * @return JsonResponse
  453.      */
  454.     public function updateAccountProfileAction(Request $request$type)
  455.     {
  456.         $formOptions = [];
  457.         $languages $this->getDoctrine()->getRepository(Language::class)->getByLanguageListArray(
  458.             array_column($this->getParameter('languages'), 'code')
  459.         );
  460.         switch ( $type ) {
  461.             case 'profile':
  462.             {
  463.                 $formOptions = [
  464.                     'destination'       => [ 'step-1''step-3''names' ],
  465.                     'include_birthday'  => true,
  466.                     'email_repeat'      => false,
  467.                     'password_repeat'   => true,
  468.                     'email_disabled'    => true,
  469.                     'username_disabled' => true,
  470.                     'include_language'  => true,
  471.                     'locale'            => $request->getLocale(),
  472.                     'languages'         => array_combine(
  473.                         array_column($languages'name'), 
  474.                         array_column($languages'id')
  475.                     )
  476.                 ];
  477.                 break;
  478.             }
  479.             
  480.             case 'notifications':
  481.             {
  482.                 $formOptions = [ 'destination' => [ 'notifications' ], 'locale' => $request->getLocale() ];
  483.                 break;
  484.             }
  485.             
  486.             case 'personalize':
  487.             {
  488.                 $this->get('session')->set('last_friend_suggestion_update'null);
  489.                 $this->get('session')->set('friend_suggestion_ids'null);
  490.                 
  491.                 $formOptions = [ 'destination' => [ 'personalize' ], 'locale' => $request->getLocale() ];
  492.                 break;
  493.             }
  494.         }
  495.         
  496.         $resp = [ 'status' => true ];
  497.         
  498.         if ( $request->getMethod() === 'POST' ) {
  499.             $em $this->get('doctrine.orm.entity_manager');
  500.             
  501.             $user $this->getUser();
  502.             
  503.             /** @var UserSignupPollData $userPollSignUp */
  504.             $userPollSignUp $this->getDoctrine()->getRepository(UserSignupPollData::class)
  505.                                    ->findOneBy([ 'userReference' => $user->getId() ]);
  506.             
  507.             
  508.             if ( $userPollSignUp ) {
  509.                 if ( $userPollSignUp->getPollReference() ) {
  510.                     /** @var TrafficPool $trafficPoll */
  511.                     $trafficPoll $userPollSignUp->getPollReference();
  512.                     $conversions $trafficPoll->getConversions();
  513.                     
  514.                     try {
  515.                         if ($conversions) {
  516.                             /** @var Conversions $conversion */
  517.                             foreach ($conversions as $conversion) {
  518.                                 if ( $conversion->getActive() ) {
  519.                                     $client = new Client();
  520.                                     $random time().mt_rand(10009999999);
  521.                                     $url $conversion->getUrl();
  522.                                     $url .= '&cb='.$random;
  523.                                     $url .= '&cti='.$user->getId(); //.'-'.$trafficPoll->getCode();
  524.                                     $this->get('sentry.client')->captureMessage($url);
  525.                                     $response $client->get($url);
  526.                                     $this->get('sentry.client')->captureMessage($response->getStatusCode());
  527.                                 }
  528.                             }
  529.                         }
  530.                     } catch ( \Exception $exception ) {
  531.                         $this->get('sentry.client')->captureException($exception);
  532.                     }
  533.                 }
  534.             }
  535.             
  536.             $form $this->createForm(
  537.                 UserType::class,
  538.                 $user,
  539.                 $formOptions
  540.             );
  541.             
  542.             $requestParams $request->get('user');
  543.             
  544.             $email $user->getEmail();
  545.             $oldUsername $user->getUsername();
  546.             $oldGender $user->getGender();
  547.             
  548.             $form->submit($requestParams);
  549.             
  550.             $user->setEmail($email);
  551.             $user->setUsername($oldUsername);
  552.             
  553.             if ( $form->isValid() ) {
  554.                 $userManager $this->container->get('fos_user.user_manager');
  555.                 $userManager->updateUser($user);
  556.                 
  557.                 $em->persist($user);
  558.                 $em->flush();
  559.                 
  560.                 if ( $oldUsername != $user->getUsername() ) {
  561.                     $this->get('social.mailer')->sendAdminUsernameChangeNotification($user$oldUsername);
  562.                 }
  563.                 if ( $oldGender != $user->getGender() ) {
  564.                     $this->get('social.mailer')->sendAdminGenderChangeNotification($user$oldGender);
  565.                 }
  566.                 
  567.                 $resp['update']['type'] = $type;
  568.                 $resp['update']['profile']['right_sidebar'] = $this->renderView(
  569.                     'SocialFrontendBundle:Components/Account:right_sidebar.html.twig'
  570.                 );
  571.                 $resp['update']['personalize']['motto'] = $user->getMotto();
  572.             } else {
  573.                 $resp['status'] = false;
  574.                 $resp['errors'] = $this->get('social.tools')->getFormErrors($form);
  575.             }
  576.         }
  577.         
  578.         return new JsonResponse($resp);
  579.     }
  580.     public function friendSuggestionsAction()
  581.     {
  582.         $em $this->get('doctrine.orm.entity_manager');
  583.         $nbrMembersOnline $em->getRepository('SocialUserBundle:User')->getNumberOfMembersOnline();
  584.         
  585.         $lastFriendSuggestionUpdate $this->get('session')->get('last_friend_suggestion_update'null);
  586.         $friendSuggestionIds $this->get('session')->get('friend_suggestion_ids'null);
  587.         
  588.         $now time();
  589.         $shouldDoNewFriendSuggestionUpdate $lastFriendSuggestionUpdate != null ? (($now $lastFriendSuggestionUpdate) >= 300 true false) : true;
  590.         if ( $shouldDoNewFriendSuggestionUpdate ) {
  591.             $friendSuggestionIds $this->get('social.friend_manager')->getFriendSuggestions($this->getUser());
  592.             $this->get('session')->set('friend_suggestion_ids'$friendSuggestionIds);
  593.             $this->get('session')->set('last_friend_suggestion_update'$now);
  594.         }
  595.         $friendSuggestion null;
  596.         if ( count($friendSuggestionIds) ) {
  597.             //            $viewedUser = $this->get('social.accessibility_manager')->getViewedUser();
  598.             $viewedUser $this->getUser() ? $this->getUser()->getViewingUser() : null;
  599.             
  600.             if ( !$viewedUser ) {
  601.                 $friendSuggestions $em->getRepository('SocialUserBundle:User')->findBy(
  602.                     [
  603.                         'id' => array_column(
  604.                             array_slice(
  605.                                 $friendSuggestionIds,
  606.                                 0,
  607.                                 6
  608.                             ),
  609.                             'id'
  610.                         ),
  611.                     ]
  612.                 );
  613.             } else {
  614.                 $viewedUserId $viewedUser->getId();
  615.                 $position = -1;
  616.                 foreach ( $friendSuggestionIds as $_pos => $friendSuggestionId ) {
  617.                     if ( $friendSuggestionId['id'] == $viewedUserId ) {
  618.                         $position $_pos;
  619.                         break;
  620.                     }
  621.                 }
  622.                 
  623.                 $min $position 2;
  624.                 if ( $min ) {
  625.                     $min 0;
  626.                 }
  627.                 $beforeAdded $position $min;
  628.                 
  629.                 $max $position + ($beforeAdded);
  630.                 if ( $max count($friendSuggestionIds) ) {
  631.                     $max count($friendSuggestionIds);
  632.                 }
  633.                 if ( $max $min ) {
  634.                     /**
  635.                      * try to move the min
  636.                      */
  637.                     $diff - ($max $min);
  638.                     
  639.                     if ( $min $diff >= && isset($friendSuggestionIds[$diff 1]) ) {
  640.                         $min $min $diff;
  641.                     }
  642.                 }
  643.                 
  644.                 $_backupFriendSuggestions array_slice($friendSuggestionIds$min$max $min);
  645.                 
  646.                 $friendSuggestions $em->getRepository('SocialUserBundle:User')->findBy(
  647.                     [
  648.                         'id' => array_column(
  649.                             $_backupFriendSuggestions,
  650.                             'id'
  651.                         ),
  652.                     ]
  653.                 );
  654.             }
  655.             return $this->render(
  656.                 'SocialFrontendBundle:Components/Account:friend_suggestions.html.twig',
  657.                 [
  658.                     'friend_suggestions' => $friendSuggestions,
  659.                     'nbr_members_online' => $nbrMembersOnline,
  660.                 ]
  661.             );
  662.         }
  663.         return new Response();
  664.     }
  665.     public function getBoostedUsersAction()
  666.     {
  667.         $em $this->get('doctrine.orm.entity_manager');
  668.         $user $this->getUser() && $this->getUser()->getViewingUser() ? $this->getUser()->getViewingUser() : $this->getUser();
  669.         $filters['current_user'] = $user;
  670.         $filters['boost_limit'] = 4;
  671.         $qb $em->getRepository(User::class)->getBoostedUsers($filters);
  672.         $boostedUsers $qb->getQuery()->execute();
  673.         return $this->render(
  674.             'SocialFrontendBundle:Components/Account:boosted_users.html.twig', [
  675.                 'boostedUsers' => $boostedUsers,
  676.             ]
  677.         );
  678.     }
  679.     public function friendSuggestionsAndBoostedProfileAction()
  680.     {
  681.         $em $this->get('doctrine.orm.entity_manager');
  682.         $nbrMembersOnline $em->getRepository('SocialUserBundle:User')->getNumberOfMembersOnline();
  683.         $lastFriendSuggestionUpdate $this->get('session')->get('last_friend_suggestion_update'null);
  684.         $friendSuggestionIds $this->get('session')->get('friend_suggestion_ids'null);
  685.         $now time();
  686.         $shouldDoNewFriendSuggestionUpdate $lastFriendSuggestionUpdate != null ? (($now $lastFriendSuggestionUpdate) >= 300 true false) : true;
  687.         if ( $shouldDoNewFriendSuggestionUpdate ) {
  688.             $friendSuggestionIds $this->get('social.friend_manager')->getFriendSuggestions($this->getUser());
  689.             $this->get('session')->set('friend_suggestion_ids'$friendSuggestionIds);
  690.             $this->get('session')->set('last_friend_suggestion_update'$now);
  691.         }
  692.         $friendSuggestion null;
  693.         if ( count($friendSuggestionIds) ) {
  694.             //            $viewedUser = $this->get('social.accessibility_manager')->getViewedUser();
  695.             $viewedUser $this->getUser() ? $this->getUser()->getViewingUser() : null;
  696.             if ( !$viewedUser ) {
  697.                 $friendSuggestions $em->getRepository('SocialUserBundle:User')->findBy(
  698.                     [
  699.                         'id' => array_column(
  700.                             array_slice(
  701.                                 $friendSuggestionIds,
  702.                                 0,
  703.                                 6
  704.                             ),
  705.                             'id'
  706.                         ),
  707.                     ]
  708.                 );
  709.             } else {
  710.                 $viewedUserId $viewedUser->getId();
  711.                 $position = -1;
  712.                 foreach ( $friendSuggestionIds as $_pos => $friendSuggestionId ) {
  713.                     if ( $friendSuggestionId['id'] == $viewedUserId ) {
  714.                         $position $_pos;
  715.                         break;
  716.                     }
  717.                 }
  718.                 $min $position 2;
  719.                 if ( $min ) {
  720.                     $min 0;
  721.                 }
  722.                 $beforeAdded $position $min;
  723.                 $max $position + ($beforeAdded);
  724.                 if ( $max count($friendSuggestionIds) ) {
  725.                     $max count($friendSuggestionIds);
  726.                 }
  727.                 if ( $max $min ) {
  728.                     /**
  729.                      * try to move the min
  730.                      */
  731.                     $diff - ($max $min);
  732.                     if ( $min $diff >= && isset($friendSuggestionIds[$diff 1]) ) {
  733.                         $min $min $diff;
  734.                     }
  735.                 }
  736.                 $_backupFriendSuggestions array_slice($friendSuggestionIds$min$max $min);
  737.                 $friendSuggestions $em->getRepository('SocialUserBundle:User')->findBy(
  738.                     [
  739.                         'id' => array_column(
  740.                             $_backupFriendSuggestions,
  741.                             'id'
  742.                         ),
  743.                     ]
  744.                 );
  745.             }
  746.             $friendSuggestion $this->renderView(
  747.                 'SocialFrontendBundle:Components/Account:friend_suggestions.html.twig',
  748.                 [
  749.                     'friend_suggestions' => $friendSuggestions,
  750.                     'nbr_members_online' => $nbrMembersOnline,
  751.                 ]
  752.             );
  753.         }
  754.         $user $this->getUser() && $this->getUser()->getViewingUser() ? $this->getUser()->getViewingUser() : $this->getUser();
  755.         $filters['current_user'] = $user;
  756.         $filters['boost_limit'] = 4;
  757.         $qb $em->getRepository(User::class)->getBoostedUsers($filters);
  758.         $boostedUsers $qb->getQuery()->execute();
  759.         $boostedUsersData $this->renderView(
  760.             'SocialFrontendBundle:Components/Account:boosted_users.html.twig', [
  761.                 'boostedUsers' => $boostedUsers,
  762.             ]
  763.         );
  764.         return new JsonResponse(['boostedUsers' => $boostedUsersData'friendSuggestions' => $friendSuggestion]);
  765.     }
  766.     /**
  767.      * @param Request $request
  768.      *
  769.      * @return JsonResponse
  770.      * @throws Exception
  771.      * @throws Twig_Error
  772.      */
  773.     public function userMarkUnreadAlertsAction(Request $request)
  774.     {
  775.         try {
  776.             $em $this->get('doctrine.orm.entity_manager');
  777.             
  778.             $user $this->getUser();
  779.             $user->sethasUnreadAlerts(false);
  780.             
  781.             foreach ( $user->getUnreadAlerts() as $alert ) {
  782.                 $alert->setIsRead(true);
  783.                 
  784.                 $em->persist($alert);
  785.             }
  786.             
  787.             $em->persist($user);
  788.             $em->flush();
  789.         } catch ( Exception $e ) {
  790.             $this->get('social.mailer')->sendAdminSystemError($e->getMessage().': '.$e->getTraceAsString());
  791.         }
  792.         
  793.         return new JsonResponse([ 'status' => true ]);
  794.     }
  795.     
  796.     /**
  797.      * @param Request $request
  798.      *
  799.      * @return Response
  800.      */
  801.     public function whoViewProfileAction(Request $request)
  802.     {
  803.         $em $this->get('doctrine.orm.entity_manager');
  804.         
  805.         $currentUser $this->getUser();
  806.         if (!$currentUser) {
  807.             $currentUser $this->get('social.accessibility_manager')->getViewedUser();
  808.         }
  809.         $currentUser->setTotalNbrUnseenProfileViews(0);
  810.         $currentUser->setHasUnseenProfileViews(0);
  811.         
  812.         $em->persist($currentUser);
  813.         $em->flush();
  814.         
  815.         return $this->render('SocialFrontendBundle:Account:who_viewed_profile.html.twig');
  816.     }
  817.     
  818.     /**
  819.      * @param Request $request
  820.      *
  821.      * @return JsonResponse|RedirectResponse
  822.      */
  823.     public function markUnlockingProfileViewAction(Request $requestUserActionManager $userActionManager)
  824.     {
  825.         // If the user is not logged in or this request is not Ajax redirect to account for login
  826.         if ( !$request->isXmlHttpRequest() ) {
  827.             return new RedirectResponse($this->generateUrl('social_frontend_account'));
  828.         }
  829.         
  830.         if ( !$this->getUser() ) {
  831.             return $this->json(
  832.                 [
  833.                     'error_flag' => true,
  834.                     'redirect'   => $this->generateUrl(
  835.                         'social_frontend_account',
  836.                         null,
  837.                         UrlGeneratorInterface::ABSOLUTE_URL
  838.                     ),
  839.                     'show_modal' => false,
  840.                     'message'    => 'You must be logged in!',
  841.                     'permission' => UserActionManager::PERMISSION_DENIED,
  842.                 ]
  843.             );
  844.         }
  845.         
  846.         /** @var User $currentUser */
  847.         $currentUser $this->getUser();
  848.         /** @var \Doctrine\ORM\EntityManagerInterface $em */
  849.         $em $this->get('doctrine.orm.entity_manager');
  850.         $profileViewId $request->get('profile_view_id'null);
  851.         
  852.         if ( null === $profileViewId ) {
  853.             return $this->json(
  854.                 [
  855.                     'error_flag' => true,
  856.                     'permission' => UserActionManager::PERMISSION_DENIED,
  857.                     'message'    => 'Invalid profile',
  858.                     'show_modal' => false,
  859.                     'redirect'   => $this->generateUrl(
  860.                         'social_frontend_account',
  861.                         null,
  862.                         UrlGeneratorInterface::ABSOLUTE_URL
  863.                     ),
  864.                 ]
  865.             );
  866.         }
  867.         
  868.         $profileView $em->getRepository('SocialFrontendBundle:ProfileView')->find($profileViewId);
  869.         
  870.         if ( $profileView === null ) {
  871.             return $this->json(
  872.                 [
  873.                     'error_flag' => true,
  874.                     'permission' => UserActionManager::PERMISSION_DENIED,
  875.                     'message'    => 'Invalid profile',
  876.                     'show_modal' => false,
  877.                     'redirect'   => $this->generateUrl(
  878.                         'social_frontend_account',
  879.                         null,
  880.                         UrlGeneratorInterface::ABSOLUTE_URL
  881.                     ),
  882.                 ]
  883.             );
  884.         }
  885.         $grantPermission $userActionManager->decideUserActionPermission(
  886.             CreditActionsEntity::CREDIT_ACTION_SEE_VISITOR,
  887.             $currentUser,
  888.             true
  889.         );
  890.         
  891.         if ( $grantPermission['permission'] === UserActionManager::PERMISSION_GRANTED ) {
  892.             $em->getRepository('SocialFrontendBundle:ProfileView')
  893.                ->removeRestrictionForParingUsers($profileView->getFromUser(), $this->getUser());
  894.             // Refresh the record since it will unlock it
  895.             $em->refresh($profileView);
  896.             $jsonResponse = [
  897.                 'html'       => $this->renderView(
  898.                     '@SocialFrontend/Account/ProfileViews/partials/profile_view_card.twig',
  899.                     [
  900.                         'user'          => $profileView->getFromUser(),
  901.                         'isLocked'      => $profileView->getLocked(),
  902.                         'profileViewId' => $profileViewId,
  903.                         'identifier'    => 'hidd-uniq-'.$profileView->getFromUser()->getId(),
  904.                     ]
  905.                 ),
  906.                 'identifier' => 'hidd-uniq-'.$profileView->getFromUser()->getId(),
  907.             ];
  908.             
  909.             return $this->json(array_merge($grantPermission$jsonResponse));
  910.         }
  911.         
  912.         
  913.         $profileView $em->getRepository('SocialFrontendBundle:ProfileView')->find($profileViewId);
  914.         
  915.         $profileView->setForUnlockAfterPayment(1);
  916.         $profileView->setForUnlockSetDate(new DateTime());
  917.         
  918.         $em->persist($profileView);
  919.         $em->flush();
  920.         
  921.         return new JsonResponse(
  922.             [
  923.                 'error_flag'    => false,
  924.                 'permission'    => 'denied',
  925.                 'credits'       => $this->getUser()->getCredits(),
  926.                 'bonus_credits' => $this->getUser()->getBonusCredits(),
  927.                 'package'       => $this->getUser()->getPackageName(),
  928.                 'message'       => $this->get('translator')->trans(
  929.                     "You don't have enough credit! Purchase one of the packages below to keep in touch with your friends."
  930.                 ),
  931.                 'callback'      => 'showPaymentModal',
  932.                 'show_modal'    => true,
  933.             ]
  934.         );
  935.     }
  936.     
  937.     /**
  938.      * @param Request $request
  939.      *
  940.      * @return JsonResponse
  941.      */
  942.     public function loadProfileViewsAction(Request $request)
  943.     {
  944.         $em $this->get('doctrine.orm.entity_manager');
  945.         $type $request->get('type');
  946.         $currentPage $request->get('page'1);
  947.         
  948.         $qb $em->getRepository('SocialFrontendBundle:ProfileView')->getQueryBuilderProfileViewsByType(
  949.             $this->getUser(),
  950.             $type
  951.         );
  952.         
  953.         
  954.         $total $qb->select('count(pv.id)')->getQuery()->getSingleScalarResult();
  955.         
  956.         $filters['limit'] = 6;
  957.         $filters['page'] = $currentPage;
  958.         $filters['offset'] = ($filters['page'] - 1) * $filters['limit'];
  959.         
  960.         //        print_r($filters);
  961.         //        die('');
  962.         
  963.         $qb $em->getRepository('SocialFrontendBundle:ProfileView')->getQueryBuilderProfileViewsByType(
  964.             $this->getUser(),
  965.             $type,
  966.             $filters
  967.         );
  968.         $profileViews $qb->getQuery()->execute();
  969.         
  970.         $totalPages ceil($total $filters['limit']);
  971.         
  972.         $options = [
  973.             'currentPage' => $filters['page'],
  974.             'total'       => $total,
  975.             'lastPage'    => $totalPages,
  976.         ];
  977.         
  978.         $requestFilters = [ 'type' => $type ];
  979.         
  980.         return new JsonResponse(
  981.             [
  982.                 'type'       => $type,
  983.                 'html'       => $this->renderView(
  984.                     'SocialFrontendBundle:Account/ProfileViews:profile_view_area.html.twig',
  985.                     [ 'type' => $type'profile_views' => $profileViews ]
  986.                 ),
  987.                 'pagination' => $this->renderView(
  988.                     'SocialFrontendBundle:Components:pagination.html.twig',
  989.                     [
  990.                         'filters'   => $requestFilters,
  991.                         'options'   => $options,
  992.                         'routeName' => 'social_account_load_profile_views',
  993.                         'sort'      => null,
  994.                         'sort_type' => null,
  995.                     ]
  996.                 ),
  997.             ]
  998.         );
  999.     }
  1000.     
  1001.     /**
  1002.      * @param Request $request
  1003.      *
  1004.      * @return Response
  1005.      */
  1006.     public function usersManagementAction(Request $request)
  1007.     {
  1008.         $user $this->getUser();
  1009.         
  1010.         if ( $user && $user->getIsFake() == true ) {
  1011.             $staff $user->getOwner();
  1012.             
  1013.             $fakes $staff->getFakesForImpersonating();
  1014.             
  1015.             return $this->render('SocialFrontendBundle:Account:users_management.html.twig', [ 'fakes' => $fakes ]);
  1016.         }
  1017.         
  1018.         return new Response();
  1019.     }
  1020.     
  1021.     /**
  1022.      * @param Request $request
  1023.      *
  1024.      * @return JsonResponse|Response
  1025.      */
  1026.     public function getUsersManagementDataAction(Request $request)
  1027.     {
  1028.         $em $this->get('doctrine.orm.entity_manager');
  1029.         $ts $request->get('ts');
  1030.         $authorizationChecker $this->get('security.authorization_checker');
  1031.         
  1032.         if ( $authorizationChecker->isGranted('ROLE_PREVIOUS_ADMIN') ) {
  1033.             $tsDateTime = new DateTime();
  1034.             $tsDateTime->setTimestamp($ts);
  1035.             
  1036.             $twig $this->get('twig');
  1037.             $user $this->getUser();
  1038.             if ( $user->getIsFake() == true ) {
  1039.                 $staff $user->getOwner();
  1040.                 $data = [];
  1041.                 $users $em->getRepository('SocialUserBundle:User')->findForStaff($staff$ts);
  1042.                 
  1043.                 foreach ( $users as $user ) {
  1044.                     $data[$user->getId()]['has_unread_alerts'] = $user->getHasUnreadAlerts();
  1045.                 }
  1046.                 
  1047.                 return new JsonResponse([ 'status' => true'data' => $data ]);
  1048.             }
  1049.         }
  1050.         
  1051.         return new JsonResponse([ 'status' => false ]);
  1052.     }
  1053.     
  1054.     /**
  1055.      * @param Request $request
  1056.      * @param         $alerts
  1057.      *
  1058.      * @return Response
  1059.      */
  1060.     public function renderAlertContentAction(Request $request$alerts)
  1061.     {
  1062.         $twig $this->get('twig');
  1063.         $alertContents = [];
  1064.         foreach ( $alerts as $alert ) {
  1065.             $templateContent $twig->loadTemplate(
  1066.                 'SocialFrontendBundle:Components/Alert:type_'.$alert->getType().'.html.twig'
  1067.             );
  1068.             $alertContent strip_tags($templateContent->renderBlock('alert_content', [ 'alert' => $alert ]));
  1069.             
  1070.             $alertContents[] = $alertContent;
  1071.         }
  1072.         
  1073.         return $this->render(
  1074.             'SocialFrontendBundle:Account:alert_render_content.html.twig',
  1075.             [ 'alert_contents' => $alertContents ]
  1076.         );
  1077.     }
  1078.     
  1079.     
  1080.     /**
  1081.      * @param Request                       $request
  1082.      * @param AuthorizationCheckerInterface $authorizationChecker
  1083.      * @param EventDispatcherInterface      $eventDispatcher
  1084.      * @param TokenStorageInterface         $tokenStorage
  1085.      * @param EntityManagerInterface        $entityManager
  1086.      * @param ClientInterface               $client
  1087.      *
  1088.      * @return RedirectResponse
  1089.      */
  1090.     public function impersonateAction(
  1091.         Request $request,
  1092.         AuthorizationCheckerInterface $authorizationChecker,
  1093.         EventDispatcherInterface $eventDispatcher,
  1094.         TokenStorageInterface $tokenStorage,
  1095.         EntityManagerInterface $entityManager,
  1096.         ClientInterface $client
  1097.     )
  1098.     : RedirectResponse {
  1099.         try {
  1100.             /** @var User $currentLoggedInUser */
  1101.             $currentLoggedInUser $this->getUser();
  1102.             
  1103.             // If the user does not have the ROLE_FSTAFF at least - then throw error
  1104. //            if ( !$currentLoggedInUser->getIsFake() && !$authorizationChecker->isGranted(User::ROLE_FSTAFF) ) {
  1105. //                throw $this->createNotFoundException(
  1106. //                    sprintf(
  1107. //                        'You are not allowed to do this user #%s.',
  1108. //                        $currentLoggedInUser->getId()
  1109. //                    )
  1110. //                );
  1111. //            }
  1112.             
  1113.             // Getting the username for impersonation
  1114.             $username $request->get('username'null);
  1115.             // If the was no username given - then throw error
  1116.             if ( null == 'username' ) {
  1117.                 throw $this->createNotFoundException(sprintf("The specified users is not valid!"));
  1118.             }
  1119.             
  1120.             $user $entityManager->getRepository(User::class)
  1121.                                   ->findOneBy([ 'username' => $username ]);
  1122.             
  1123.             // If the user was not found in the database - throw error
  1124.             if ( !$user instanceof User ) {
  1125.                 throw $this->createNotFoundException(sprintf("The user %s you looked for does not exists."$username));
  1126.             }
  1127.             
  1128.             $dispatcher $eventDispatcher;
  1129.             $allowedRoles = [User::ROLE_FSTAFFUser::ROLE_HSTAFFUser::ROLE_SUBADMINUser::ROLE_ADMINUser::ROLE_SUPER_ADMIN];
  1130.             $allowedImpersonate false;
  1131.             foreach ($user->getRoles() as $role) {
  1132.                 if (in_array($role$allowedRoles)) {
  1133.                     $allowedImpersonate true;
  1134.                 }
  1135.             }
  1136.             // If the user from database is fake and has an owner then proceed to impersonate
  1137.             if ((in_array(User::ROLE_SUPER_ADMIN$currentLoggedInUser->getRoles()) && $allowedImpersonate) || ($user->getIsFake() && $user->getOwner()) ) {
  1138.                 // Getting current session token
  1139.                 $currentToken $tokenStorage->getToken();
  1140.                 
  1141.                 // Check if current session has original_impersonator
  1142.                 $originalImpersonator null;
  1143.                 if ( $currentToken->hasAttribute('original_impersonator') ) {
  1144.                     $originalImpersonator $currentToken->getAttribute('original_impersonator');
  1145.                 } else {
  1146.                     $originalImpersonator $currentLoggedInUser->getId();
  1147.                 }
  1148.                 $roles $user->getRoles();
  1149.                 $role = new SwitchUserRole('ROLE_PREVIOUS_ADMIN'$currentToken);
  1150.                 $roles[] = $role;
  1151.                 $token = new UsernamePasswordToken(
  1152.                     $usernull'main',
  1153.                     $roles
  1154.                 );
  1155.                 
  1156.                 $token->setAttribute('original_impersonator'$originalImpersonator);
  1157.                 $tokenStorage->setToken($token);
  1158.                 if (!$request->getSession()->get('_switch_user')) {
  1159.                     $request->getSession()->set('_switch_user'serialize($tokenStorage->getToken()));
  1160.                 }
  1161.                 
  1162.                 $switchEvent = new SwitchUserEvent($request$token->getUser());
  1163.                 $dispatcher->dispatch(SecurityEvents::SWITCH_USER$switchEvent);
  1164.                 if (in_array(User::ROLE_HSTAFF$user->getRoles())) {
  1165.                     return $this->redirect($this->generateUrl('social_admin_hstaff_dashboard'));
  1166.                 }
  1167.                 if (in_array(User::ROLE_FSTAFF$user->getRoles()) ||
  1168.                     in_array(User::ROLE_ADMIN$user->getRoles()) ||
  1169.                     in_array(User::ROLE_SUBADMIN$user->getRoles()) ||
  1170.                     in_array(User::ROLE_SUPER_ADMIN$user->getRoles())
  1171.                 ) {
  1172.                     return $this->redirect($this->generateUrl('social_admin_dashboard'));
  1173.                 }
  1174.                 return $this->redirect($this->generateUrl('social_frontend_homepage_account'));
  1175.             } else {
  1176.                 // The user to try and impersonate must have an owner
  1177.                 $this->addFlash('danger''The user you tried to impersonate has no owner.');
  1178.                 
  1179.                 return new RedirectResponse($this->generateUrl('admin_fake_list'));
  1180.             }
  1181.         } catch ( \Exception $exception ) {
  1182.             $client->captureException($exception);
  1183.             
  1184.             return new RedirectResponse($this->generateUrl('admin_fake_list'));
  1185.         }
  1186.     }
  1187.     /**
  1188.      * @param EntityManagerInterface $entityManager
  1189.      * @param TokenStorageInterface $tokenStorage
  1190.      * @param ClientInterface $client
  1191.      *
  1192.      * @param Request $request
  1193.      * @return RedirectResponse
  1194.      */
  1195.     public function exitImpersonationAction(
  1196.         EntityManagerInterface $entityManager,
  1197.         TokenStorageInterface $tokenStorage,
  1198.         ClientInterface $client,
  1199.         Request $request
  1200.     )
  1201.     : RedirectResponse {
  1202.         try {
  1203.             /** @var User $user */
  1204.             $user $this->getUser();
  1205.             if ( $user->getIsFake() == false ) {
  1206.                 throw $this->createNotFoundException(
  1207.                     sprintf(
  1208.                         'You are not allowed to do this user #%s.',
  1209.                         $user->getId()
  1210.                     )
  1211.                 );
  1212.             }
  1213.             $owner null;
  1214.             $currentToken $tokenStorage->getToken();
  1215.             
  1216.             $loadedUser null;
  1217.             // Check if has the original_impersonator field in token
  1218.             if ( $currentToken->hasAttribute('original_impersonator') ) {
  1219.                 $userID $currentToken->getAttribute('original_impersonator');
  1220.                 
  1221.                 $loadedUser $entityManager
  1222.                     ->getRepository(User::class)
  1223.                     ->findOneBy([ 'id' => $userID ]);
  1224.             }
  1225.             
  1226.             if ( !$loadedUser instanceof User ) {
  1227.                 foreach ( $currentToken->getRoles() as $role ) {
  1228.                     if ( $role instanceof SwitchUserRole ) {
  1229.                         /** @var User $owner */
  1230.                         $owner $role->getSource()->getUser();
  1231.                     }
  1232.                 }
  1233.                 
  1234.                 if ( $owner->getId() ) {
  1235.                     /** @var User $loadedUser */
  1236.                     $loadedUser $entityManager
  1237.                         ->getRepository(User::class)
  1238.                         ->findOneBy([ 'id' => $owner->getId() ]);
  1239.                 }
  1240.             }
  1241.             
  1242.             $token = new UsernamePasswordToken(
  1243.                 $loadedUsernull'main',
  1244.                 $loadedUser->getRoles()
  1245.             ); // 'main' is the name of the firewall
  1246.             $tokenStorage->setToken($token);
  1247.             $request->getSession()->remove('_switch_user');
  1248.             $user->setRealIsOnline(false);
  1249.             
  1250.             $entityManager->persist($user);
  1251.             $entityManager->flush();
  1252.             
  1253.             return $this->redirect($this->generateUrl('admin_fake_list'));
  1254.         } catch ( \Exception $exception ) {
  1255.             $client->captureException($exception);
  1256.             
  1257.             return $this->redirect($this->generateUrl('homepage'));
  1258.         }
  1259.     }
  1260.     
  1261.     /**
  1262.      * @param Request $request
  1263.      *
  1264.      * @return string
  1265.      */
  1266.     public function unsubscribeEmailAction(Request $request)
  1267.     {
  1268.         $emailingManager $this->get('social.emailing_manager');
  1269.         $token $request->get('token');
  1270.         
  1271.         $unsubscribed null;
  1272.         $submit $request->get('submit');
  1273.         
  1274.         if ( $submit == 'true' ) {
  1275.             $data $emailingManager->decodeToken($token);
  1276.             
  1277.             $unsubscribed false;
  1278.             if ( is_array($data) ) {
  1279.                 $unsubscribed $emailingManager->unsubscribeUserByData($data);
  1280.             }
  1281.         }
  1282.         
  1283.         return $this->render(
  1284.             'SocialFrontendBundle:Account:unsubscribe_email.html.twig',
  1285.             [
  1286.                 'unsubscribed' => $unsubscribed,
  1287.                 'submit'       => $submit,
  1288.                 'url'          => 'social_frontend_unsubscribe',
  1289.             ]
  1290.         );
  1291.     }
  1292.     
  1293.     /**
  1294.      * @param Request $request
  1295.      *
  1296.      * @return Response
  1297.      * @throws OptimisticLockException
  1298.      */
  1299.     public function unsubscribeCampaignEmailAction(Request $request)
  1300.     {
  1301.         $contactInviteManager $this->get('social_internal.contact_inviter_manager');
  1302.         $token $request->get('token');
  1303.         
  1304.         $unsubscribed null;
  1305.         $submit $request->get('submit');
  1306.         
  1307.         if ( $submit == 'true' ) {
  1308.             $data $contactInviteManager->decodeToken($token);
  1309.             
  1310.             $unsubscribed false;
  1311.             if ( is_array($data) ) {
  1312.                 $unsubscribed $contactInviteManager->unsubscribeUserByData($data);
  1313.             }
  1314.         }
  1315.         
  1316.         return $this->render(
  1317.             'SocialFrontendBundle:Account:unsubscribe_email.html.twig',
  1318.             [
  1319.                 'unsubscribed' => $unsubscribed,
  1320.                 'submit'       => $submit,
  1321.                 'url'          => 'social_email_campaign_unsubscribe',
  1322.             ]
  1323.         );
  1324.     }
  1325.     
  1326.     /**
  1327.      * @param Request $request
  1328.      *
  1329.      * @return Response
  1330.      */
  1331.     public function getPopularUsersForModalNonLoggedInAction(Request $request)
  1332.     {
  1333.         $em $this->get('doctrine.orm.entity_manager');
  1334.         $userManager $this->get('social_user.user_manager');
  1335.         
  1336.         $viewedUser null;
  1337.         if ( $this->getUser() instanceof User ) {
  1338.             $viewedUser $this->getUser()->getViewedUser();
  1339.         } else {
  1340.             $username $request->get('username');
  1341.             $viewedUser $em->getRepository('SocialUserBundle:User')->findOneByUsername($username);
  1342.         }
  1343.         
  1344.         $gender null;
  1345.         
  1346.         if ( $viewedUser != null ) {
  1347.             $gender $viewedUser->getGender();
  1348.         }
  1349.         
  1350.         $profiles $userManager->findPopularProfilesNearIpAddress(nullnullnull$gender);
  1351.         
  1352.         return $this->render(
  1353.             'SocialFrontendBundle:Components/Account:popular_users_for_modal_non_logged_in.html.twig',
  1354.             [ 'profiles' => $profiles ]
  1355.         );
  1356.     }
  1357.     
  1358.     /**
  1359.      * @param Request $request
  1360.      *
  1361.      * @return JsonResponse|Response
  1362.      * @throws DBALException
  1363.      * @throws OptimisticLockException
  1364.      * @throws Twig_Error
  1365.      */
  1366.     public function inviteAction(Request $request)
  1367.     {
  1368.         $em $this->get('doctrine.orm.entity_manager');
  1369.         if ( $request->getMethod() == 'POST' ) {
  1370.             $dataCollection $request->get('emails');
  1371.             $singleContact $request->get('single-contact');
  1372.             
  1373.             $saveableCollection = [];
  1374.             $nbrSaved 0;
  1375.             $totalErrorsFound 0;
  1376.             
  1377.             if ( count($dataCollection) ) {
  1378.                 foreach ( $dataCollection as $item ) {
  1379.                     preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i"$item$matches);
  1380.                     $name preg_replace("/\<[^)]+\>/"""$item);
  1381.                     
  1382.                     if ( isset($matches[0][0]) ) {
  1383.                         $saveableCollection[] = [
  1384.                             'email' => $matches[0][0],
  1385.                             'name'  => $name,
  1386.                         ];
  1387.                     } else {
  1388.                         $totalErrorsFound++;
  1389.                     }
  1390.                 }
  1391.                 
  1392.                 /* check how many have been submited in the last 24 hours */
  1393.                 $contactsInvitedInLast24Hours $this->get(
  1394.                     'social_internal.contact_inviter_manager'
  1395.                 )->getNbrContactsInvitedInLast24Hours($this->getUser());
  1396.                 
  1397.                 if ( $this->getParameter('single_contact_invite_max_per_24_hours') > $contactsInvitedInLast24Hours ) {
  1398.                     $nbrSaved $this->get('social_internal.contact_inviter_manager')->saveImportedContacts(
  1399.                         $this->getUser(),
  1400.                         $saveableCollection,
  1401.                         $singleContact,
  1402.                         true
  1403.                     );
  1404.                 }
  1405.             }
  1406.             
  1407.             $response = [];
  1408.             if ( count($saveableCollection) ) {
  1409.                 $response['import'] = true;
  1410.                 if ( $totalErrorsFound ) {
  1411.                     $response['has_errors'] = true;
  1412.                 } else {
  1413.                     $response['has_errors'] = false;
  1414.                 }
  1415.             } else {
  1416.                 $response['import'] = false;
  1417.             }
  1418.             $response['nbr_saved'] = $nbrSaved;
  1419.             
  1420.             return new JsonResponse($response);
  1421.         }
  1422.         $lastMessage $em->getRepository('SocialFrontendBundle:Message')->findOneBy(
  1423.             [
  1424.                 'from_user'  => $this->getUser(),
  1425.                 'is_deleted' => 0,
  1426.             ],
  1427.             [ 'created_at' => 'DESC' ]
  1428.         );
  1429.         $lastContact null;
  1430.         if ( $lastMessage ) {
  1431.             $relationship $lastMessage->getRelationship();
  1432.             $lastContact $relationship->getContact($this->getUser());
  1433.         }
  1434.         $usersToDisplay $em->getRepository('SocialUserBundle:User')->findPopularUsersForModalNonLoggedIn(
  1435.             [ $this->getUser()->getNewLocation() ],
  1436.             !$this->getUser()->getGender()
  1437.         );
  1438.         if ( $lastContact ) {
  1439.             $usersToDisplay array_slice($usersToDisplay05);
  1440.         }
  1441.         
  1442.         $form $this->createFormBuilder()
  1443.                      ->add('submitFile''file', [ 'label' => 'File to Submit''required' => true ])
  1444.                      ->getForm();
  1445.         
  1446.         return $this->render(
  1447.             'SocialFrontendBundle:Account:invite.html.twig',
  1448.             [
  1449.                 'users_to_display' => $usersToDisplay,
  1450.                 'last_contact'     => $lastContact,
  1451.                 'form'             => $form->createView(),
  1452.             ]
  1453.         );
  1454.     }
  1455.     
  1456.     /**
  1457.      * @return Response
  1458.      */
  1459.     public function confirmPackageUsageAction(Request $request)
  1460.     {
  1461.         return $this->render('SocialFrontendBundle:Account:confirm_package_usage.html.twig');
  1462.     }
  1463.     
  1464.     /**
  1465.      * @param Request $request
  1466.      *
  1467.      * @return RedirectResponse
  1468.      */
  1469.     public function acceptPackageUsageAction(Request $request)
  1470.     {
  1471.         $em $this->get('doctrine.orm.entity_manager');
  1472.         $user $this->getUser();
  1473.         
  1474.         $user->setHasAgreedToWaiveRights(true);
  1475.         $em->persist($user);
  1476.         $em->flush();
  1477.         
  1478.         return $this->redirect($this->generateUrl('social_frontend_account'));
  1479.     }
  1480.     
  1481.     /**
  1482.      * @param Request $request
  1483.      *
  1484.      * @return Response
  1485.      */
  1486.     public function channelAuthenticationAction(Request $request)
  1487.     {
  1488.         $socketId $request->get('socket_id');
  1489.         $em $this->get('doctrine.orm.entity_manager');
  1490.         
  1491.         $finalAuth = [];
  1492.         $pusher $this->container->get('social.pusher_initializer')->initialize();
  1493.         $presenceData = [ 'name' => $this->getUser()->getUserName() ];
  1494.         
  1495.         foreach ( $request->request->get('channel_name') as $roomName ) {
  1496.             $auth null;
  1497.             $status 200;
  1498.             $presenceData['id'] = $this->getUser()->getId();
  1499.             $presenceData['type'] = 'NU'// Normal User
  1500.             if ( strpos($roomName'presence-room-counter') !== false ) {
  1501.                 $auth $pusher->presence_auth(
  1502.                     $roomName,
  1503.                     $socketId,
  1504.                     $this->getUser()->getId(),
  1505.                     $presenceData
  1506.                 );
  1507.                 
  1508.                 $finalAuth[$roomName] = [
  1509.                     'status' => $status,
  1510.                     'data'   => json_decode($auth),
  1511.                 ];
  1512.                 
  1513.                 return new JsonResponse($finalAuth);
  1514.             }
  1515.             if ( strstr($roomName'presence-room-call') !== false ) {
  1516.                 $relationshipId str_replace('presence-room-call-'''$roomName);
  1517.                 
  1518.                 $relationshipIds $em->getRepository('SocialFrontendBundle:Relationship')->getRelationshipIdsForUser(
  1519.                     $this->getUser()
  1520.                 );
  1521.                 if ( !in_array($relationshipId$relationshipIds) ) {
  1522.                     //                        throw $this->createNotFoundException(sprintf('You do not belong to room id(#%s).', $relationshipIds));
  1523.                     $status 403;
  1524.                 } else {
  1525.                     $presenceData['room_id'] = $relationshipId;
  1526.                     
  1527.                     $auth $pusher->presence_auth(
  1528.                         $roomName,
  1529.                         $socketId,
  1530.                         $this->getUser()->getId(),
  1531.                         $presenceData
  1532.                     );
  1533.                 }
  1534.             } else {
  1535.                 if ( strstr($roomName'presence-room-alerts') !== false ) {
  1536.                     $userId str_replace('presence-room-alerts-'''$roomName);
  1537.                     
  1538.                     if ( $this->getUser()->getId() == $userId ) {
  1539.                         $auth $pusher->presence_auth(
  1540.                             $roomName,
  1541.                             $socketId,
  1542.                             $this->getUser()->getId(),
  1543.                             $presenceData
  1544.                         );
  1545.                     } else {
  1546.                         //                        throw $this->createNotFoundException(sprintf('Could not authenticate channel \'%s\' and socket \'%s\'', $roomName, $socketId));
  1547.                         $status 403;
  1548.                     }
  1549.                 } else {
  1550.                     if ( strstr($roomName'presence-room') !== false ) {
  1551.                         $relationshipId str_replace('presence-room-'''$roomName);
  1552.                         
  1553.                         $relationshipIds $em->getRepository(
  1554.                             'SocialFrontendBundle:Relationship'
  1555.                         )->getRelationshipIdsForUser($this->getUser());
  1556.                         if ( !in_array($relationshipId$relationshipIds) ) {
  1557.                             //                        throw $this->createNotFoundException(sprintf('You do not belong to room id(#%s).', $relationshipIds));
  1558.                             $status 403;
  1559.                         } else {
  1560.                             $presenceData['room_id'] = $relationshipId;
  1561.                             
  1562.                             $auth $pusher->presence_auth(
  1563.                                 $roomName,
  1564.                                 $socketId,
  1565.                                 $this->getUser()->getId(),
  1566.                                 $presenceData
  1567.                             );
  1568.                         }
  1569.                     } else {
  1570.                         if ( strstr($roomName'private-room-call') !== false ) {
  1571.                             $relationshipId str_replace('private-room-call-'''$roomName);
  1572.                             
  1573.                             $relationshipIds $em->getRepository(
  1574.                                 'SocialFrontendBundle:Relationship'
  1575.                             )->getRelationshipIdsForUser($this->getUser());
  1576.                             if ( !in_array($relationshipId$relationshipIds) ) {
  1577.                                 //                        throw $this->createNotFoundException(sprintf('You do not belong to room id(#%s).', $relationshipIds));
  1578.                                 $status 403;
  1579.                             } else {
  1580.                                 $presenceData['room_id'] = $relationshipId;
  1581.                                 
  1582.                                 $auth $pusher->presence_auth(
  1583.                                     $roomName,
  1584.                                     $socketId,
  1585.                                     $this->getUser()->getId(),
  1586.                                     $presenceData
  1587.                                 );
  1588.                             }
  1589.                         } else {
  1590.                             if ( strstr($roomName'private-room-alerts') !== false ) {
  1591.                                 $userId str_replace('private-room-alerts-'''$roomName);
  1592.                                 
  1593.                                 if ( $this->getUser()->getId() == $userId ) {
  1594.                                     $auth $pusher->presence_auth(
  1595.                                         $roomName,
  1596.                                         $socketId,
  1597.                                         $this->getUser()->getId(),
  1598.                                         $presenceData
  1599.                                     );
  1600.                                 } else {
  1601.                                     //                        throw $this->createNotFoundException(sprintf('Could not authenticate channel \'%s\' and socket \'%s\'', $roomName, $socketId));
  1602.                                     $status 403;
  1603.                                 }
  1604.                             } else {
  1605.                                 if ( strstr($roomName'private-room') !== false ) {
  1606.                                     $relId str_replace('private-room-'''$roomName);
  1607.                                     
  1608.                                     $relationshipIds $em->getRepository(
  1609.                                         'SocialFrontendBundle:Relationship'
  1610.                                     )->getRelationshipIdsForUser($this->getUser());
  1611.                                     if ( !in_array($relId$relationshipIds) ) {
  1612.                                         //                        throw $this->createNotFoundException(sprintf('You do not belong to room id(#%s).', $relId));
  1613.                                         $status 403;
  1614.                                     } else {
  1615.                                         $presenceData['room_id'] = $relId;
  1616.                                         
  1617.                                         $auth $pusher->presence_auth(
  1618.                                             $roomName,
  1619.                                             $socketId,
  1620.                                             $this->getUser()->getId(),
  1621.                                             $presenceData
  1622.                                         );
  1623.                                     }
  1624.                                 } else {
  1625.                                     //                    throw $this->createNotFoundException(sprintf('Could not authenticate channel \'%s\' and socket \'%s\'', $roomName, $socketId));
  1626.                                     if ( strstr($roomName'private-profile-views-alerts') !== false ) {
  1627.                                         $userId str_replace('private-profile-views-alerts-'''$roomName);
  1628.                                         
  1629.                                         if ( $this->getUser()->getId() == $userId ) {
  1630.                                             $auth $pusher->presence_auth(
  1631.                                                 $roomName,
  1632.                                                 $socketId,
  1633.                                                 $this->getUser()->getId(),
  1634.                                                 $presenceData
  1635.                                             );
  1636.                                         } else {
  1637.                                             //                        throw $this->createNotFoundException(sprintf('Could not authenticate channel \'%s\' and socket \'%s\'', $roomName, $socketId));
  1638.                                             $status 403;
  1639.                                         }
  1640.                                     } else {
  1641.                                         $status 403;
  1642.                                     }
  1643.                                 }
  1644.                             }
  1645.                         }
  1646.                     }
  1647.                 }
  1648.             }
  1649.             $finalAuth[$roomName] = [
  1650.                 'status' => $status,
  1651.                 'data'   => json_decode($auth),
  1652.             ];
  1653.         }
  1654.         
  1655.         return new JsonResponse($finalAuth);
  1656.     }
  1657.     /**
  1658.      * @param Request $request
  1659.      *
  1660.      * @return JsonResponse|Response
  1661.      */
  1662.     public function pusherWebHookAction(Request $request)
  1663.     {
  1664.         file_put_contents(
  1665.             $this->getParameter('kernel.project_dir') . '/src/Social/FrontendBundle/Controller/text.txt',
  1666.             $request->getContent()
  1667.         );
  1668.         try {
  1669.             return $this
  1670.                 ->get('social.web_hook.channel_event_handler')
  1671.                 ->handle(
  1672.                     $_SERVER['HTTP_X_PUSHER_SIGNATURE'],
  1673.                     json_decode($request->getContent(), true)
  1674.                 );
  1675.         } catch ( Exception $exception ) {
  1676.             $this->get('sentry.client')->captureMessage($exception->getMessage());
  1677.         }
  1678.     }
  1679.     
  1680.     /**
  1681.      * @param Request $request
  1682.      *
  1683.      * @return RedirectResponse
  1684.      * @throws Twig_Error
  1685.      */
  1686.     public function redirectToCamAction(Request $request)
  1687.     {
  1688.         $mailerManager $this->get('social.mailer');
  1689.         
  1690.         $mailerManager->sendAdminRedirectToCam($this->getUser());
  1691.         
  1692.         return $this->redirect($this->getParameter('bonga_cash_redirect_url'));
  1693.     }
  1694.     
  1695.     /**
  1696.      * @param Request $request
  1697.      *
  1698.      * @return JsonResponse
  1699.      */
  1700.     public function markTourAsCompletedAction(Request $request)
  1701.     : JsonResponse {
  1702.         $em $this->get('doctrine.orm.entity_manager');
  1703.         $user $this->getUser();
  1704.         
  1705.         $user->setTourCompleted(true);
  1706.         $em->persist($user);
  1707.         $em->flush();
  1708.         
  1709.         return $this->json([]);
  1710.     }
  1711.     
  1712.     /**
  1713.      * @param Request $request
  1714.      *
  1715.      * @return RedirectResponse
  1716.      * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  1717.      */
  1718.     public function confirmAccountDeletionAction(Request $request)
  1719.     {
  1720.         $em $this->get('doctrine.orm.entity_manager');
  1721.         
  1722.         $userDeletionQueue = new UserDeletionQueue();
  1723.         $userDeletionQueue->setUserId($this->getUser()->getId());
  1724.         $userDeletionQueue->setScheduledFor(new DateTime('+13 days'));
  1725.         $userDeletionQueue->setStatus(UserDeletionQueue::STATUS_NEW);
  1726.         $userDeletionQueue->setForUser($this->getUser());
  1727.         $userDeletionQueue->setSource('user_frontend');
  1728.         
  1729.         $this->getUser()->setReceiveEmailNotifications(0);
  1730.         
  1731.         /** add him to unsubscribe list */
  1732.         //$unsubscribeQueue = new UnsubscribeQueue();
  1733.         //$unsubscribeQueue->setForUser($this->getUser());
  1734.         //$unsubscribeQueue->setStatus(UnsubscribeQueue::STATUS_NEW);
  1735.         //$unsubscribeQueue->setScheduledFor(new \DateTime('+10 days'));
  1736.         //$unsubscribeQueue->setProcessorName('centralPay');
  1737.         //$em->persist($unsubscribeQueue);
  1738.         /** @var Payment $userLastPayment */
  1739.         $userLastPayment $em->getRepository(Payment::class)
  1740.             ->findOneBy(['from_user' => $this->getUser()], ['id' => 'DESC']);
  1741.         if ($userLastPayment) {
  1742.             if ($userLastPayment->getGatewayName() == 'Cardbilling') {
  1743.                 $verotelInstallmentRecord $em->getRepository(VerotelConfirmationPayment::class)
  1744.                     ->findOneBy(['from_user' => $userLastPayment->getFromUser(), 'payment_status' => 'ACCEPTED'], ['id' => 'DESC']);
  1745.                 if ($verotelInstallmentRecord) {
  1746.                     $this->get('social_internal.payments.verotel_card')->cancelSubscription($verotelInstallmentRecord->getSaleID(), 'deleted_front_end''Backend');
  1747.                 }
  1748.             } elseif ($userLastPayment->getGatewayName() == 'centralPay_SF') {
  1749.                 $centralPaySFConfirmationPayment $em->getRepository(CentralPaySFConfirmationPayment::class)
  1750.                     ->find($userLastPayment->getCpsfInstallmentId());
  1751.                 if ($centralPaySFConfirmationPayment) {
  1752.                     $this->get('social_internal.payments.centralpay_provider_v2')->cancelSFPaymentSubscription($this->getUser(), $centralPaySFConfirmationPayment'account_deleted''frontend');
  1753.                 }
  1754.             } elseif ($userLastPayment->getGatewayName() == 'CentralPay') {
  1755.                 $this->get('social_internal.payments.centralpay_provider_v2')->cancelCentralPaySubscription($this->getUser());
  1756.             } else {
  1757.                 $centralPayService $this->get('social_internal.payments.centralpay_provider_v2')
  1758.                     ->processHookRequest(
  1759.                         [
  1760.                             'internalType' => HookUtility::INTERNAL_ACTION_USER_ACCOUNT_DELETE,
  1761.                             'user'         => $this->getUser(),
  1762.                         ]
  1763.                     );
  1764.                 if ( $centralPayService['error_flag'] == false ) {
  1765.                     $userDeletionQueue->setPaymentReference($centralPayService['merchantTransactionId']);
  1766.                 }
  1767.             }
  1768.         }
  1769.         $em->persist($userDeletionQueue);
  1770.         $em->persist($this->getUser());
  1771.         
  1772.         $em->flush();
  1773.         
  1774.         $this->container->get('security.token_storage')->setToken(null);
  1775.         
  1776.         return $this->redirect($this->generateUrl('social_user_homepage'));
  1777.     }
  1778.     
  1779.     //    public function smtpNotificationAction(Request $request)
  1780.     //    {
  1781.     //        $logDir = $this->get('kernel')->getLogDir();
  1782.     //        file_put_contents($logDir . '/' . 'sendinblue.log', serialize($request->request->all()) . "\r\n" . serialize($request->query->all()) . "\r\n -------" . "\r\n", FILE_APPEND);
  1783.     //
  1784.     //        return new JsonResponse();
  1785.     //    }
  1786.     
  1787.     public function importSendEmailsAction(Request $request)
  1788.     {
  1789.         $emails $request->get('emails');
  1790.         
  1791.         $emailsCollection explode(','$emails);
  1792.         $validEmails = [];
  1793.         $validator = new EmailValidator();
  1794.         $translator $this->get('translator');
  1795.         $contactInviterManager $this->get('social_internal.contact_inviter_manager');
  1796.         
  1797.         foreach ( $emailsCollection as $email ) {
  1798.             $email trim($email" \t\n\r\0\x0B,./<>?;:\\\"|[]{}!@#$%^&*()_+-=~`");
  1799.             
  1800.             if ( $validator->isValid($email, new RFCValidation()) ) {
  1801.                 $validEmails[] = $email;
  1802.             }
  1803.         }
  1804.         
  1805.         $data = [];
  1806.         foreach ( $validEmails as $validEmail ) {
  1807.             $data[] = [ 'email' => $validEmail'name' => '' ];
  1808.         }
  1809.         
  1810.         $contactInviterManager->saveImportedContacts($this->getUser(), $datafalsetrue);
  1811.         
  1812.         if ( count($validEmails) ) {
  1813.             return new JsonResponse([ 'status' => true'emails_count' => count($validEmails) ]);
  1814.         } else {
  1815.             return new JsonResponse(
  1816.                 [
  1817.                     'status'        => false,
  1818.                     'error_message' => $translator->trans('You have not submitted any valid email.'),
  1819.                 ]
  1820.             );
  1821.         }
  1822.     }
  1823.     
  1824.     public function importUploadCsvAction(Request $request)
  1825.     {
  1826.         $toolsManager $this->get('social.tools');
  1827.         $contactInviterManager $this->get('social_internal.contact_inviter_manager');
  1828.         
  1829.         $form $this->createFormBuilder()
  1830.                      ->add(
  1831.                          'submitFile',
  1832.                          'file',
  1833.                          [
  1834.                              'label'       => 'File to Submit',
  1835.                              'required'    => true,
  1836.                              'constraints' => [
  1837.                                  new File(
  1838.                                      [
  1839.                                          'maxSize'          => '1M',
  1840.                                          'mimeTypes'        => [
  1841.                                              'text/csv',
  1842.                                              'text/plain',
  1843.                                          ],
  1844.                                          'mimeTypesMessage' => 'Please upload a valid CSV file',
  1845.                                      ]
  1846.                                  ),
  1847.                              ],
  1848.                          ]
  1849.                      )
  1850.                      ->getForm();
  1851.         
  1852.         if ( $request->getMethod() == 'POST' ) {
  1853.             // Bind request to the form
  1854.             $form->handleRequest($request);
  1855.             
  1856.             // If form is valid
  1857.             if ( $form->isValid() ) {
  1858.                 // Get file
  1859.                 $file $form->get('submitFile');
  1860.                 
  1861.                 // Your csv file here when you hit submit button
  1862.                 $fileData $file->getData();
  1863.                 $content $toolsManager->CSVToArray($fileData);
  1864.                 
  1865.                 foreach ( $content as $rowNbr => $rowData ) {
  1866.                     if ( isset($rowData['E-mail 1 - Value']) ) {
  1867.                         $email trim(
  1868.                             $rowData['E-mail 1 - Value'],
  1869.                             " \t\n\r\0\x0B,./<>?;:\\\"|[]{}!@#$%^&*()_+-=~`"
  1870.                         );
  1871.                         $content[$rowNbr]['email'] = $email;
  1872.                     }
  1873.                     if ( isset($rowData['Name']) ) {
  1874.                         $content[$rowNbr]['name'] = $rowData['Name'];
  1875.                     }
  1876.                 }
  1877.                 
  1878.                 $contactInviterManager->saveImportedContacts($this->getUser(), $contentfalsetrue);
  1879.                 
  1880.                 return $this->redirect($this->generateUrl('social_invite', [ 'csv_upload' => true ]));
  1881.             } else {
  1882.                 return $this->redirect($this->generateUrl('social_invite', [ 'csv_error' => true ]));
  1883.             }
  1884.         }
  1885.     }
  1886.     public function boostProfileAction(UserActionManager $userActionManager)
  1887.     {
  1888.         $em $this->getDoctrine()->getManager();
  1889.         /** @var User $user */
  1890.         $user $this->getUser();
  1891.         /** @var CreditActionsEntity $creditAction */
  1892.         $creditAction $em->getRepository(CreditActionsEntity::class)->findOneBy(['code' => CreditActionsEntity::CREDIT_ACTION_BOOST_PROFILE]);
  1893.         $historyCreditUsage = new CreditUserHistoryEntity();
  1894.         $historyCreditUsage->setUserId($user);
  1895.         $historyCreditUsage->setCost($creditAction->getCost());
  1896.         $historyCreditUsage->setIsFromBonus(false);
  1897.         $historyCreditUsage->setAction(CreditActionsEntity::CREDIT_ACTION_BOOST_PROFILE);
  1898.         $historyCreditUsage->setTimestamp(new \DateTime('now'));
  1899.         $historyCreditUsage->setType(CreditUserHistoryEntity::ACTION_TYPE_SUBTRACT);
  1900.         $credit $user->getCredits() - $creditAction->getCost();
  1901.         $user->setCredits($credit);
  1902.         $user->setProfileBoosted(true);
  1903.         $user->setBoostedAt(new \DateTime('now'));
  1904.         $boostProfileHistory = new UserBoostProfileHistory();
  1905.         $boostProfileHistory->setUser($user);
  1906.         $boostProfileHistory->setCreatedAt(new \DateTime('now'));
  1907.         $boostProfileHistory->setUpdatedAt(new \DateTime('now'));
  1908.         $em->persist($boostProfileHistory);
  1909.         $em->persist($historyCreditUsage);
  1910.         $em->persist($user);
  1911.         $em->flush();
  1912.         $validForOpenModal $userActionManager->validForOpenProfileConfirmationModal($user);
  1913.         return new JsonResponse(['status' => true'message' => 'Boosted Successfully!''open_profile_confirmation_modal' => $validForOpenModal]);
  1914.     }
  1915.     public function cancelDeletionRequestAction()
  1916.     {
  1917.         $em $this->getDoctrine()->getManager();
  1918.         /** @var User $user */
  1919.         $user $this->getUser();
  1920.         /** @var UserDeletionQueue $userDeletionQue */
  1921.         $userDeletionQue $em->getRepository(UserDeletionQueue::class)->findOneBy(['for_user' => $user'isDeleted' => false]);
  1922.         $userDeletionQue->setIsDeleted(true);
  1923.         $em->persist($userDeletionQue);
  1924.         $em->flush();
  1925.         $this->get('social.alert_manager')->createAlertCancelledDeletionRequest(
  1926.             $user,
  1927.             $user
  1928.         );
  1929.         return new JsonResponse(['status' => true'message' => 'Cancelled Deletion Request Successfully!']);
  1930.     }
  1931.     public function bootLiveAction(Request $request)
  1932.     {
  1933.         try {
  1934.             $request->get('_route');
  1935.             $em $this->getDoctrine()->getManager();
  1936.             $bootLiveType $request->get('action');
  1937.             if (isset($bootLiveType) && $bootLiveType == 'signup') {
  1938.                 $type BootProfile::Boot_sign_up;
  1939.             } else {
  1940.                 $type BootProfile::Boot_online;
  1941.             }
  1942.             $currentUser $em->getRepository('SocialUserBundle:User')->find($this->getUser()->getId());
  1943.             $bootLiveProfileList $em->getRepository('SocialInternalBundle:BootProfile')->findBy(
  1944.                 [
  1945.                     'bootType' => BootProfile::LIVE_ACTION,
  1946.                     'bootLiveType' => $type,
  1947.                     'isActionComplted' => false,
  1948.                     'isDraft' => false,
  1949.                 ], ['timeInterval' => 'ASC']);
  1950.             $toUserList[] = $this->getUser();
  1951.             for ($i 0$i count($bootLiveProfileList); $i++) {
  1952. //                $interval = $bootLiveProfileList[$i]->getTimeInterval();
  1953. //                if ($i > 0) {
  1954. //                    $interval = $bootLiveProfileList[$i]->getTimeInterval() - $bootLiveProfileList[$i-1]->getTimeInterval();
  1955. //                }
  1956. //                sleep($interval * 60);
  1957.                 $staffUser $em->getRepository('SocialUserBundle:User')->find($bootLiveProfileList[$i]->getCreatedBy());
  1958.                 $isUserValidForBoot $em->getRepository('SocialInternalBundle:EmailList')->findOneBy(
  1959.                     ['to_user' => $staffUser'signed_up_user' => $currentUser]);
  1960.                 if (isset($isUserValidForBoot)) {
  1961.                     $this->liveAction($bootLiveProfileList[$i], $toUserList);
  1962.                 }
  1963.             }
  1964.             return new JsonResponse(['error' => false]);
  1965.         } catch (Exception $exception) {
  1966.             return new JsonResponse(['error' => true'error_message' => $exception->getMessage()]);
  1967.         }
  1968.     }
  1969.     public function liveAction($bootProfileRecord$toUserList) {
  1970.         $bootActionManager $this->container->get('social_internal.boot_action_manager');
  1971.         foreach ($bootProfileRecord->getActionString() as $action) {
  1972.             switch ($action)
  1973.             {
  1974.                 case 'SEND_MESSAGE':
  1975.                     $actionResult $bootActionManager->sendMessageAction($bootProfileRecord$toUserListtrue);
  1976.                     break;
  1977.                 case 'VIEW_PROFILE':
  1978.                     $actionResult $bootActionManager->viewProfileAction($bootProfileRecord$toUserListtrue);
  1979.                     break;
  1980.                 case 'SEND_FRIEND_REQUEST':
  1981.                     $actionResult $bootActionManager->sendFriendRequestAction($bootProfileRecord$toUserListtrue);
  1982.                     break;
  1983.                 case 'SWIPE':
  1984.                     $actionResult $bootActionManager->swipeAction($bootProfileRecord$toUserListtrue);
  1985.                     break;
  1986.             }
  1987.         }
  1988.     }
  1989. }