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

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