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

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