<?php
namespace Social\FrontendBundle\Controller;
use DateTime;
use Doctrine\DBAL\DBALException;
use Social\CreditsBundle\Entity\CreditActionsEntity;
use Social\CreditsBundle\Entity\CreditUserHistoryEntity;
use Social\FrontendBundle\Entity\AlertsUserToast;
use Social\FrontendBundle\Entity\CentralPaySFConfirmationPayment;
use Social\FrontendBundle\Entity\Payment;
use Social\FrontendBundle\Entity\SwipeHistory;
use Social\FrontendBundle\Entity\VerotelConfirmationPayment;
use Social\FrontendBundle\Service\UserActionManager;
use Social\InternalBundle\Entity\BootProfile;
use Social\InternalBundle\Entity\PackagesList;
use Social\InternalBundle\Entity\SuperBot;
use Social\InternalBundle\Entity\UserBoostProfileHistory;
use Social\UserBundle\Form\UserType;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\OptimisticLockException;
use Exception;
use GuzzleHttp\Client;
use Egulias\EmailValidator\Validation\RFCValidation;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Social\InternalBundle\Entity\TrafficPoll\Conversions;
use Social\InternalBundle\Entity\TrafficPool;
use Social\InternalBundle\Entity\UserDeletionQueue;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Social\InternalBundle\Service\PaymentMethods\CentralPay\HookUtility;
use Social\UserBundle\Entity\User;
use Social\UserBundle\Entity\UserComponents\UserSignupPollData;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Validator\Constraints\File;
use Egulias\EmailValidator\EmailValidator;
use Social\InternalBundle\Entity\Language;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* Class AccountController
*
* @package Social\FrontendBundle\Controller
*/
class AccountController extends Controller
{
/**
* @param Request $request
* @param EntityManagerInterface $entityManager
*
* @return Response
* @throws OptimisticLockException
*/
public function accountAction(Request $request, EntityManagerInterface $entityManager): Response
{
$em = $entityManager;
/** @var User $currentUser */
$currentUser = $this->getUser();
$form = null;
$goInTrafficPollFlag = false;
if ( !$currentUser ) {
$form = $this->createForm(
UserType::class,
null,
[ 'include_birthday' => true, 'include_agree' => true ]
);
$form = $form->createView();
$goInTrafficPollFlag = true;
/** @var User $user */
$user = $this->get('social.accessibility_manager')->getViewedUser();
if ( !$user ) {
throw $this->createNotFoundException(
sprintf(
'There is no user with the "%s"',
$request->get('username')
)
);
}
} else {
if ( $this->getUser() && $this->getUser() instanceof User) {
$user = $this->getUser()->getViewedUser();
} else {
$user = null;
}
}
// Check if current user has location
if ( $currentUser && $currentUser instanceof User && $currentUser->getIsFake() != true && $currentUser->getOwner() == null ) {
if ( $currentUser->getNewLocation() == null ) {
$userIP = $request->getClientIp();
$locale = $request->getLocale();
$userLocationTrack = $this->get('social_internal.ip_track_manager')->getLocationForIp($userIP);
$userLocation = $this->get('social_internal.ip_track_manager')->getLocationFromDBForUserObject(
$userLocationTrack,
$locale
);
if ( $userLocation != null ) {
if ( is_array($userLocation) ) {
$beforeLocation = $user->getNewLocation();
if ( $beforeLocation == null ) {
try {
/** @var UserSignupPollData $userPollSignUp */
$userPollSignUp = $this->getDoctrine()->getRepository(UserSignupPollData::class)
->findOneBy([ 'userReference' => $user ]);
if ( $userPollSignUp ) {
if ( $userPollSignUp->getPollReference() ) {
/** @var TrafficPool $trafficPoll */
$trafficPoll = $userPollSignUp->getPollReference();
$conversions = $trafficPoll->getConversions();
if ($conversions) {
/** @var Conversions $conversion */
foreach ($conversions as $conversion) {
if ($conversion->getActive()) {
$client = new Client();
$random = time() + random_int(1, 9999);
$url = $conversion->getUrl();
$url .= '&cb='.$random;
$url .= '&cti='.$user->getId().'-'.$trafficPoll->getCode();
$this->get('sentry.client')->captureMessage($url);
$response = $client->get($url);
$this->get('sentry.client')->captureMessage($response->getStatusCode());
}
}
}
}
}
} catch ( Exception $exception ) {
$this->get('sentry.client')->captureException($exception);
}
}
}
}
$em->persist($user);
$em->flush();
}
}
if ( $currentUser instanceof UserInterface ) {
if ( $user && $user->getId() != $currentUser->getId() ) {
if ( !$this->get('social.accessibility_manager')->canUserViewProfile($currentUser, $user) ) {
throw new UsernameNotFoundException();
}
$this->get('social.profile_view_manager')->visitProfile($currentUser, $user);
$this->get('social.alert_manager')->createAlertViewedProfile($currentUser, $user);
if ($request->get('isSwiped') && $request->get('isSwiped') == 1) {
$existSwipeHistory = $em->getRepository(SwipeHistory::class)->findOneBy(['toUser' => $user, 'fromUser' => $currentUser, 'event' => SwipeHistory::EVENT_PROFILE_VIEWED]);
if (!$existSwipeHistory) {
$swipeHistory = new SwipeHistory();
$swipeHistory->setEvent(SwipeHistory::EVENT_PROFILE_VIEWED);
$swipeHistory->setFromUser($currentUser);
$swipeHistory->setToUser($user);
$em->persist($swipeHistory);
$em->flush();
}
}
}
}
$response = $this->render(
'SocialFrontendBundle:Account:account.html.twig',
[ 'user' => $user, 'form' => $form ]
);
if ( $goInTrafficPollFlag ) {
$trafficPollIncomeCode = $request->get('upi');
if ($request->get('upi')) {
$singleTraffic = $entityManager->getRepository(TrafficPool::class)->findOneBy(['code' => $request->get('upi')]);
if ($singleTraffic) {
if ( $singleTraffic->getPollType() == TrafficPool::POLL_TYPE_USER_PAGE && $singleTraffic->getCode() == $trafficPollIncomeCode ) {
$urlParams = $singleTraffic->getUrlParameters();
foreach ( $urlParams as $single ) {
$value = $request->get($single->getKeyValue(), null);
if ( $value != null ) {
$cookie = new Cookie(
'tfpr['.$single->getKeyValue().']', $value, 0, '/', null, false,
false
);
$response->headers->setCookie($cookie);
}
}
$cookie = new Cookie('tfpr[pollId]', $singleTraffic->getId(), 0, '/', null, false, false);
$response->headers->setCookie($cookie);
}
}
}
}
if ($currentUser && $user->getIsFake() && ($user !== $this->getUser())) {
$this->get('social.super_bot_manager')->triggerSuperBot(SuperBot::VIEW_PROFILE, $currentUser, $user);
}
return $response;
}
public function triggerNotificationAction(EntityManagerInterface $entityManager)
{
try {
$user = $this->getUser();
if ($user) {
$bubbleAlerts = $entityManager->getRepository('SocialFrontendBundle:AlertsUserToast')->getUserAlerts($user, 4);
$pusher = $this->container->get('social.pusher_initializer')->initialize();
$templating = $this->container->get('templating');
foreach ($bubbleAlerts as $bubbleAlert) {
$date = $bubbleAlert->getCreatedAt();
$dateTime = new \DateTime($date->format('Y-m-d H:i:s'), new \DateTimeZone('Europe/Bucharest'));
$user1 = $bubbleAlert->getFromUser();
$user2 = $bubbleAlert->getToUser();
$visit = $bubbleAlert->getType() == AlertsUserToast::ALERT_TYPE_PROFILE_VIEW;
$url = $this->getBubbleUrl($bubbleAlert->getType(), $bubbleAlert);
$action = AlertsUserToast::getAlertLabel($bubbleAlert->getType());
$type = AlertsUserToast::getAlertLabel($bubbleAlert->getType());
$message = $bubbleAlert->getMessage();
if ($bubbleAlert->getType() == AlertsUserToast::ALERT_TYPE_PROFILE_VIEW) {
$message = str_replace($user1->getUsername(), '<a class="blurry-text">' . $user1->getUsername() . '</a>', $message);
}
$action_key = $bubbleAlert->getType();
$pusher->trigger(
'bubble-notifications-' . $user2->getId(),
'payload',
[
'username' => $user1->getUsername(),
'profile_picture' => $templating->render(
'SocialFrontendBundle::user_image.html.twig',
['user' => $user1, 'visit' => $visit]
),
'url' => $url,
'to_user' => $user2->getUsername(),
'picture' => '<i class="fas fa-eye"></i>',
'action' => $action,
'type' => $type,
'message' => $message,
'time' => $date->format('Y-m-d H:i:s'),
'timestamp' => $dateTime->getTimestamp(),
'action_key' => $action_key,
'alert_notification_id' => $bubbleAlert->getId()
]
);
$bubbleAlert->setIsUserOnline(true);
$bubbleAlert->setIsSent(true);
$entityManager->persist($bubbleAlert);
$entityManager->flush();
sleep(2);
}
}
return new JsonResponse(['error' => false]);
} catch (Exception $exception) {
return new JsonResponse(['error' => true]);
}
}
public function onBubbleNotificationClickAction(Request $request, EntityManagerInterface $entityManager)
{
try {
$alertId = $request->request->get('alertId');
$alertToast = $entityManager->getRepository('SocialFrontendBundle:AlertsUserToast')->find($alertId);
if ($alertToast) {
$alertToast->setIsRead(true);
$entityManager->persist($alertToast);
$entityManager->flush();
}
return new JsonResponse('true');
} catch (Exception $exception) {
return new JsonResponse(['error' => true]);
}
}
public function removeBubbleNotificationAction(Request $request, EntityManagerInterface $entityManager)
{
try {
$alertId = $request->request->get('alertId');
$alertToast = $entityManager->getRepository('SocialFrontendBundle:AlertsUserToast')->find($alertId);
$entityManager->remove($alertToast);
$entityManager->flush();
return new JsonResponse('true');
} catch (Exception $exception) {
return new JsonResponse(['error' => true]);
}
}
public function onBubbleNotificationClickCloseAction(Request $request, EntityManagerInterface $entityManager)
{
try {
$alertId = $request->request->get('alertId');
$alertToast = $entityManager->getRepository('SocialFrontendBundle:AlertsUserToast')->find($alertId);
$alertToast->setIsClosed(true);
$entityManager->persist($alertToast);
$entityManager->flush();
return new JsonResponse('true');
} catch (Exception $exception) {
return new JsonResponse(['error' => true]);
}
}
public function getBubbleUrl($type, $bubbleAlert)
{
$this->router = $this->container->get('router');
$likesComments = [
AlertsUserToast::ALERT_TYPE_VIDEO_LIKE,
AlertsUserToast::ALERT_TYPE_VIDEO_COMMENT,
AlertsUserToast::ALERT_TYPE_PHOTO_COMMENT,
AlertsUserToast::ALERT_TYPE_PHOTO_LIKE,
];
if (in_array($type, $likesComments)) {
return $this->router->generate(
'social_frontend_user_photo',
array(
'username' => $bubbleAlert->getToUser()->getUsername(),
'photo_id' => $bubbleAlert->getToUser()->getImage()->getId(),
)
).'#comment-area';
}
switch ($type) {
case AlertsUserToast::ALERT_TYPE_PROFILE_VIEW:
return $this->router->generate('social_account_who_viewed_my_profile');
case AlertsUserToast::ALERT_TYPE_FRIEND_REQUEST:
return $this->router->generate('social_frontend_user_friends', ['username' => $bubbleAlert->getFromUser()->getUsername()]);
case AlertsUserToast::ALERT_TYPE_FRIEND_APPROVED:
return $this->router->generate(
'social_frontend_user_about',
array('username' => $bubbleAlert->getFromUser()->getUsername()));
case AlertsUserToast::ALERT_TYPE_MESSAGE:
return $this->router->generate('social_frontend_chat_with_friend',
array('username' => $bubbleAlert->getFromUser()->getUsername()));
}
}
/**
* @return Response
*/
public function detailsAction()
: Response
{
return $this->render('SocialFrontendBundle:Account:details.html.twig');
}
/**
* @param Request $request
*
* @return Response
*/
public function updateProfileDetailsAction(Request $request)
{
$languages = $this->getDoctrine()->getRepository(Language::class)->getByLanguageListArray(
array_column($this->getParameter('languages'), 'code')
);
$form = $this->createForm(
UserType::class,
$this->getUser(),
[
'destination' => [ 'step-1', 'step-3', 'names' ],
'include_birthday' => true,
'email_repeat' => false,
'password_repeat' => true,
'email_disabled' => true,
'username_disabled' => true,
'include_language' => true,
'locale' => strtolower($request->getLocale()),
'languages' => array_combine(
array_column($languages, 'name'),
array_column($languages, 'id')
)
]
);
return $this->render(
'SocialFrontendBundle:Account/Profile:update_profile_details.html.twig',
[ 'form' => $form->createView() ]
);
}
/**
* @param Request $request
*
* @return Response
*/
public function updateNotificationPreferencesAction(Request $request)
{
$form = $this->createForm(
UserType::class,
$this->getUser(),
[ 'destination' => [ 'notifications' ], 'locale' => $request->getLocale() ]
);
return $this->render(
'SocialFrontendBundle:Account/Profile:update_notification_preferences.html.twig',
[ 'form' => $form->createView() ]
);
}
/**
* @param Request $request
*
* @return Response
*/
public function updatePersonalizeAccountAction(Request $request)
{
$form = $this->createForm(
UserType::class,
$this->getUser(),
[ 'destination' => [ 'personalize' ], 'locale' => $request->getLocale() ]
);
return $this->render(
'SocialFrontendBundle:Account/Profile:update_personalize_account.html.twig',
[ 'form' => $form->createView() ]
);
}
/**
* @param EntityManagerInterface $entityManager
*
* @return Response
*/
public function displayPaymentHistoryAction(EntityManagerInterface $entityManager)
: Response {
$paymentHistory = $entityManager->getRepository('SocialFrontendBundle:Payment')->findBy(
[ 'from_user' => $this->getUser() ],
[ 'created_at' => 'desc' ]
);
return $this->render(
'SocialFrontendBundle:Account/Profile:display_payment_history.html.twig',
[ 'payment_history' => $paymentHistory ]
);
}
/**
* @return Response
*/
public function displaySubscriptionOptionsAction()
{
if ( $this->getUser() instanceof User ) {
$packageName = $this->getUser()->getPackageName();
} else {
$packageName = null;
}
return $this->render(
'SocialFrontendBundle:Account/Profile:display_subscription_options.html.twig', [
'package_name' => $packageName,
]
);
}
/**
* @param Request $request
* @param $type
*
* @return JsonResponse
*/
public function updateAccountProfileAction(Request $request, $type)
{
$formOptions = [];
$languages = $this->getDoctrine()->getRepository(Language::class)->getByLanguageListArray(
array_column($this->getParameter('languages'), 'code')
);
switch ( $type ) {
case 'profile':
{
$formOptions = [
'destination' => [ 'step-1', 'step-3', 'names' ],
'include_birthday' => true,
'email_repeat' => false,
'password_repeat' => true,
'email_disabled' => true,
'username_disabled' => true,
'include_language' => true,
'locale' => $request->getLocale(),
'languages' => array_combine(
array_column($languages, 'name'),
array_column($languages, 'id')
)
];
break;
}
case 'notifications':
{
$formOptions = [ 'destination' => [ 'notifications' ], 'locale' => $request->getLocale() ];
break;
}
case 'personalize':
{
$this->get('session')->set('last_friend_suggestion_update', null);
$this->get('session')->set('friend_suggestion_ids', null);
$formOptions = [ 'destination' => [ 'personalize' ], 'locale' => $request->getLocale() ];
break;
}
}
$resp = [ 'status' => true ];
if ( $request->getMethod() === 'POST' ) {
$em = $this->get('doctrine.orm.entity_manager');
$user = $this->getUser();
/** @var UserSignupPollData $userPollSignUp */
$userPollSignUp = $this->getDoctrine()->getRepository(UserSignupPollData::class)
->findOneBy([ 'userReference' => $user->getId() ]);
if ( $userPollSignUp ) {
if ( $userPollSignUp->getPollReference() ) {
/** @var TrafficPool $trafficPoll */
$trafficPoll = $userPollSignUp->getPollReference();
$conversions = $trafficPoll->getConversions();
try {
if ($conversions) {
/** @var Conversions $conversion */
foreach ($conversions as $conversion) {
if ( $conversion->getActive() ) {
$client = new Client();
$random = time().mt_rand(1000, 9999999);
$url = $conversion->getUrl();
$url .= '&cb='.$random;
$url .= '&cti='.$user->getId(); //.'-'.$trafficPoll->getCode();
$this->get('sentry.client')->captureMessage($url);
$response = $client->get($url);
$this->get('sentry.client')->captureMessage($response->getStatusCode());
}
}
}
} catch ( \Exception $exception ) {
$this->get('sentry.client')->captureException($exception);
}
}
}
$form = $this->createForm(
UserType::class,
$user,
$formOptions
);
$requestParams = $request->get('user');
$email = $user->getEmail();
$oldUsername = $user->getUsername();
$oldGender = $user->getGender();
$form->submit($requestParams);
$user->setEmail($email);
$user->setUsername($oldUsername);
if ( $form->isValid() ) {
$userManager = $this->container->get('fos_user.user_manager');
$userManager->updateUser($user);
$em->persist($user);
$em->flush();
if ( $oldUsername != $user->getUsername() ) {
$this->get('social.mailer')->sendAdminUsernameChangeNotification($user, $oldUsername);
}
if ( $oldGender != $user->getGender() ) {
$this->get('social.mailer')->sendAdminGenderChangeNotification($user, $oldGender);
}
$resp['update']['type'] = $type;
$resp['update']['profile']['right_sidebar'] = $this->renderView(
'SocialFrontendBundle:Components/Account:right_sidebar.html.twig'
);
$resp['update']['personalize']['motto'] = $user->getMotto();
} else {
$resp['status'] = false;
$resp['errors'] = $this->get('social.tools')->getFormErrors($form);
}
}
return new JsonResponse($resp);
}
public function friendSuggestionsAction()
{
$em = $this->get('doctrine.orm.entity_manager');
$nbrMembersOnline = $em->getRepository('SocialUserBundle:User')->getNumberOfMembersOnline();
$friendSuggestions = $this->getSuggestedFriends();
if (count($friendSuggestions)) {
return $this->render(
'SocialFrontendBundle:Components/Account:friend_suggestions.html.twig',
[
'friend_suggestions' => $friendSuggestions,
'nbr_members_online' => $nbrMembersOnline,
]
);
}
return new Response();
}
public function getBoostedUsersAction()
{
$em = $this->get('doctrine.orm.entity_manager');
$user = $this->getUser() && $this->getUser()->getViewingUser() ? $this->getUser()->getViewingUser() : $this->getUser();
$filters['current_user'] = $user;
$filters['boost_limit'] = 4;
$qb = $em->getRepository(User::class)->getBoostedUsers($filters);
$boostedUsers = $qb->getQuery()->execute();
return $this->render(
'SocialFrontendBundle:Components/Account:boosted_users.html.twig', [
'boostedUsers' => $boostedUsers,
]
);
}
public function friendSuggestionsAndBoostedProfileAction()
{
$em = $this->get('doctrine.orm.entity_manager');
$nbrMembersOnline = $em->getRepository('SocialUserBundle:User')->getNumberOfMembersOnline();
$lastFriendSuggestionUpdate = $this->get('session')->get('last_friend_suggestion_update', null);
$friendSuggestionIds = $this->get('session')->get('friend_suggestion_ids', null);
$now = time();
$shouldDoNewFriendSuggestionUpdate = $lastFriendSuggestionUpdate != null ? (($now - $lastFriendSuggestionUpdate) >= 300 ? true : false) : true;
if ( $shouldDoNewFriendSuggestionUpdate ) {
$friendSuggestionIds = $this->get('social.friend_manager')->getFriendSuggestions($this->getUser());
$this->get('session')->set('friend_suggestion_ids', $friendSuggestionIds);
$this->get('session')->set('last_friend_suggestion_update', $now);
}
$friendSuggestion = null;
if ( count($friendSuggestionIds) ) {
// $viewedUser = $this->get('social.accessibility_manager')->getViewedUser();
$viewedUser = $this->getUser() ? $this->getUser()->getViewingUser() : null;
if ( !$viewedUser ) {
$friendSuggestions = $em->getRepository('SocialUserBundle:User')->findBy(
[
'id' => array_column(
array_slice(
$friendSuggestionIds,
0,
6
),
'id'
),
]
);
} else {
$viewedUserId = $viewedUser->getId();
$position = -1;
foreach ( $friendSuggestionIds as $_pos => $friendSuggestionId ) {
if ( $friendSuggestionId['id'] == $viewedUserId ) {
$position = $_pos;
break;
}
}
$min = $position - 2;
if ( $min < 0 ) {
$min = 0;
}
$beforeAdded = $position - $min;
$max = $position + 3 + (3 - $beforeAdded);
if ( $max > count($friendSuggestionIds) ) {
$max = count($friendSuggestionIds);
}
if ( $max - $min < 6 ) {
/**
* try to move the min
*/
$diff = 6 - ($max - $min);
if ( $min - $diff >= 0 && isset($friendSuggestionIds[$diff - 1]) ) {
$min = $min - $diff;
}
}
$_backupFriendSuggestions = array_slice($friendSuggestionIds, $min, $max - $min);
$friendSuggestions = $em->getRepository('SocialUserBundle:User')->findBy(
[
'id' => array_column(
$_backupFriendSuggestions,
'id'
),
]
);
}
$friendSuggestion = $this->renderView(
'SocialFrontendBundle:Components/Account:friend_suggestions.html.twig',
[
'friend_suggestions' => $friendSuggestions,
'nbr_members_online' => $nbrMembersOnline,
]
);
}
$user = $this->getUser() && $this->getUser()->getViewingUser() ? $this->getUser()->getViewingUser() : $this->getUser();
$filters['current_user'] = $user;
$filters['boost_limit'] = 4;
$qb = $em->getRepository(User::class)->getBoostedUsers($filters);
$boostedUsers = $qb->getQuery()->execute();
$boostedUsersData = $this->renderView(
'SocialFrontendBundle:Components/Account:boosted_users.html.twig', [
'boostedUsers' => $boostedUsers,
]
);
return new JsonResponse(['boostedUsers' => $boostedUsersData, 'friendSuggestions' => $friendSuggestion]);
}
/**
* @param Request $request
*
* @return JsonResponse
* @throws Exception
* @throws Twig_Error
*/
public function userMarkUnreadAlertsAction(Request $request)
{
try {
$em = $this->get('doctrine.orm.entity_manager');
$user = $this->getUser();
$user->sethasUnreadAlerts(false);
foreach ( $user->getUnreadAlerts() as $alert ) {
$alert->setIsRead(true);
$em->persist($alert);
}
$em->persist($user);
$em->flush();
} catch ( Exception $e ) {
$this->get('social.mailer')->sendAdminSystemError($e->getMessage().': '.$e->getTraceAsString());
}
return new JsonResponse([ 'status' => true ]);
}
/**
* @param Request $request
*
* @return Response
*/
public function whoViewProfileAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$currentUser = $this->getUser();
if (!$currentUser) {
$currentUser = $this->get('social.accessibility_manager')->getViewedUser();
}
$currentUser->setTotalNbrUnseenProfileViews(0);
$currentUser->setHasUnseenProfileViews(0);
$em->persist($currentUser);
$em->flush();
return $this->render('SocialFrontendBundle:Account:who_viewed_profile.html.twig');
}
/**
* @param Request $request
*
* @return JsonResponse|RedirectResponse
*/
public function markUnlockingProfileViewAction(Request $request, UserActionManager $userActionManager)
{
// If the user is not logged in or this request is not Ajax redirect to account for login
if ( !$request->isXmlHttpRequest() ) {
return new RedirectResponse($this->generateUrl('social_frontend_account'));
}
if ( !$this->getUser() ) {
return $this->json(
[
'error_flag' => true,
'redirect' => $this->generateUrl(
'social_frontend_account',
null,
UrlGeneratorInterface::ABSOLUTE_URL
),
'show_modal' => false,
'message' => 'You must be logged in!',
'permission' => UserActionManager::PERMISSION_DENIED,
]
);
}
/** @var User $currentUser */
$currentUser = $this->getUser();
/** @var \Doctrine\ORM\EntityManagerInterface $em */
$em = $this->get('doctrine.orm.entity_manager');
$profileViewId = $request->get('profile_view_id', null);
if ( null === $profileViewId ) {
return $this->json(
[
'error_flag' => true,
'permission' => UserActionManager::PERMISSION_DENIED,
'message' => 'Invalid profile',
'show_modal' => false,
'redirect' => $this->generateUrl(
'social_frontend_account',
null,
UrlGeneratorInterface::ABSOLUTE_URL
),
]
);
}
$profileView = $em->getRepository('SocialFrontendBundle:ProfileView')->find($profileViewId);
if ( $profileView === null ) {
return $this->json(
[
'error_flag' => true,
'permission' => UserActionManager::PERMISSION_DENIED,
'message' => 'Invalid profile',
'show_modal' => false,
'redirect' => $this->generateUrl(
'social_frontend_account',
null,
UrlGeneratorInterface::ABSOLUTE_URL
),
]
);
}
$grantPermission = $userActionManager->decideUserActionPermission(
CreditActionsEntity::CREDIT_ACTION_SEE_VISITOR,
$currentUser,
true
);
if ( $grantPermission['permission'] === UserActionManager::PERMISSION_GRANTED ) {
$em->getRepository('SocialFrontendBundle:ProfileView')
->removeRestrictionForParingUsers($profileView->getFromUser(), $this->getUser());
// Refresh the record since it will unlock it
$em->refresh($profileView);
$jsonResponse = [
'html' => $this->renderView(
'@SocialFrontend/Account/ProfileViews/partials/profile_view_card.twig',
[
'user' => $profileView->getFromUser(),
'isLocked' => $profileView->getLocked(),
'profileViewId' => $profileViewId,
'identifier' => 'hidd-uniq-'.$profileView->getFromUser()->getId(),
]
),
'identifier' => 'hidd-uniq-'.$profileView->getFromUser()->getId(),
];
return $this->json(array_merge($grantPermission, $jsonResponse));
}
$profileView = $em->getRepository('SocialFrontendBundle:ProfileView')->find($profileViewId);
$profileView->setForUnlockAfterPayment(1);
$profileView->setForUnlockSetDate(new DateTime());
$em->persist($profileView);
$em->flush();
return new JsonResponse(
[
'error_flag' => false,
'permission' => 'denied',
'credits' => $this->getUser()->getCredits(),
'bonus_credits' => $this->getUser()->getBonusCredits(),
'package' => $this->getUser()->getPackageName(),
'message' => $this->get('translator')->trans(
"You don't have enough credit! Purchase one of the packages below to keep in touch with your friends."
),
'callback' => 'showPaymentModal',
'show_modal' => true,
]
);
}
/**
* @param Request $request
*
* @return JsonResponse
*/
public function loadProfileViewsAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$type = $request->get('type');
$currentPage = $request->get('page', 1);
$qb = $em->getRepository('SocialFrontendBundle:ProfileView')->getQueryBuilderProfileViewsByType(
$this->getUser(),
$type
);
$total = $qb->select('count(pv.id)')->getQuery()->getSingleScalarResult();
$filters['limit'] = 6;
$filters['page'] = $currentPage;
$filters['offset'] = ($filters['page'] - 1) * $filters['limit'];
// print_r($filters);
// die('');
$qb = $em->getRepository('SocialFrontendBundle:ProfileView')->getQueryBuilderProfileViewsByType(
$this->getUser(),
$type,
$filters
);
$profileViews = $qb->getQuery()->execute();
$totalPages = ceil($total / $filters['limit']);
$options = [
'currentPage' => $filters['page'],
'total' => $total,
'lastPage' => $totalPages,
];
$requestFilters = [ 'type' => $type ];
return new JsonResponse(
[
'type' => $type,
'html' => $this->renderView(
'SocialFrontendBundle:Account/ProfileViews:profile_view_area.html.twig',
[ 'type' => $type, 'profile_views' => $profileViews ]
),
'pagination' => $this->renderView(
'SocialFrontendBundle:Components:pagination.html.twig',
[
'filters' => $requestFilters,
'options' => $options,
'routeName' => 'social_account_load_profile_views',
'sort' => null,
'sort_type' => null,
]
),
]
);
}
/**
* @param Request $request
*
* @return Response
*/
public function usersManagementAction(Request $request)
{
$user = $this->getUser();
if ( $user && $user->getIsFake() == true ) {
$staff = $user->getOwner();
$fakes = $staff->getFakesForImpersonating();
return $this->render('SocialFrontendBundle:Account:users_management.html.twig', [ 'fakes' => $fakes ]);
}
return new Response();
}
/**
* @param Request $request
*
* @return JsonResponse|Response
*/
public function getUsersManagementDataAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$ts = $request->get('ts');
$authorizationChecker = $this->get('security.authorization_checker');
if ( $authorizationChecker->isGranted('ROLE_PREVIOUS_ADMIN') ) {
$tsDateTime = new DateTime();
$tsDateTime->setTimestamp($ts);
$twig = $this->get('twig');
$user = $this->getUser();
if ( $user->getIsFake() == true ) {
$staff = $user->getOwner();
$data = [];
$users = $em->getRepository('SocialUserBundle:User')->findForStaff($staff, $ts);
foreach ( $users as $user ) {
$data[$user->getId()]['has_unread_alerts'] = $user->getHasUnreadAlerts();
}
return new JsonResponse([ 'status' => true, 'data' => $data ]);
}
}
return new JsonResponse([ 'status' => false ]);
}
/**
* @param Request $request
* @param $alerts
*
* @return Response
*/
public function renderAlertContentAction(Request $request, $alerts)
{
$twig = $this->get('twig');
$alertContents = [];
foreach ( $alerts as $alert ) {
$templateContent = $twig->loadTemplate(
'SocialFrontendBundle:Components/Alert:type_'.$alert->getType().'.html.twig'
);
$alertContent = strip_tags($templateContent->renderBlock('alert_content', [ 'alert' => $alert ]));
$alertContents[] = $alertContent;
}
return $this->render(
'SocialFrontendBundle:Account:alert_render_content.html.twig',
[ 'alert_contents' => $alertContents ]
);
}
/**
* @param Request $request
* @param AuthorizationCheckerInterface $authorizationChecker
* @param EventDispatcherInterface $eventDispatcher
* @param TokenStorageInterface $tokenStorage
* @param EntityManagerInterface $entityManager
*
* @return RedirectResponse
*/
public function impersonateAction(
Request $request,
AuthorizationCheckerInterface $authorizationChecker,
EventDispatcherInterface $eventDispatcher,
TokenStorageInterface $tokenStorage,
EntityManagerInterface $entityManager
)
: RedirectResponse {
try {
/** @var User $currentLoggedInUser */
$currentLoggedInUser = $this->getUser();
// If the user does not have the ROLE_FSTAFF at least - then throw error
// if ( !$currentLoggedInUser->getIsFake() && !$authorizationChecker->isGranted(User::ROLE_FSTAFF) ) {
// throw $this->createNotFoundException(
// sprintf(
// 'You are not allowed to do this user #%s.',
// $currentLoggedInUser->getId()
// )
// );
// }
// Getting the username for impersonation
$username = $request->get('username', null);
// If the was no username given - then throw error
if ( null == 'username' ) {
throw $this->createNotFoundException(sprintf("The specified users is not valid!"));
}
$user = $entityManager->getRepository(User::class)
->findOneBy([ 'username' => $username ]);
// If the user was not found in the database - throw error
if ( !$user instanceof User ) {
throw $this->createNotFoundException(sprintf("The user %s you looked for does not exists.", $username));
}
$dispatcher = $eventDispatcher;
$allowedRoles = [User::ROLE_FSTAFF, User::ROLE_HSTAFF, User::ROLE_SUBADMIN, User::ROLE_ADMIN, User::ROLE_SUPER_ADMIN];
$allowedImpersonate = false;
foreach ($user->getRoles() as $role) {
if (in_array($role, $allowedRoles)) {
$allowedImpersonate = true;
}
}
// If the user from database is fake and has an owner then proceed to impersonate
if ((in_array(User::ROLE_SUPER_ADMIN, $currentLoggedInUser->getRoles()) && $allowedImpersonate) || ($user->getIsFake() && $user->getOwner()) ) {
// Getting current session token
$currentToken = $tokenStorage->getToken();
// Check if current session has original_impersonator
$originalImpersonator = null;
if ( $currentToken->hasAttribute('original_impersonator') ) {
$originalImpersonator = $currentToken->getAttribute('original_impersonator');
} else {
$originalImpersonator = $currentLoggedInUser->getId();
}
$roles = $user->getRoles();
$role = new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $currentToken);
$roles[] = $role;
$token = new UsernamePasswordToken(
$user, null, 'main',
$roles
);
$token->setAttribute('original_impersonator', $originalImpersonator);
$tokenStorage->setToken($token);
if (!$request->getSession()->get('_switch_user')) {
$request->getSession()->set('_switch_user', serialize($tokenStorage->getToken()));
}
$switchEvent = new SwitchUserEvent($request, $token->getUser());
$dispatcher->dispatch(SecurityEvents::SWITCH_USER, $switchEvent);
if (in_array(User::ROLE_HSTAFF, $user->getRoles())) {
return $this->redirect($this->generateUrl('social_admin_hstaff_dashboard'));
}
if (in_array(User::ROLE_FSTAFF, $user->getRoles()) ||
in_array(User::ROLE_ADMIN, $user->getRoles()) ||
in_array(User::ROLE_SUBADMIN, $user->getRoles()) ||
in_array(User::ROLE_SUPER_ADMIN, $user->getRoles())
) {
return $this->redirect($this->generateUrl('social_admin_dashboard'));
}
return $this->redirect($this->generateUrl('social_frontend_homepage_account'));
} else {
// The user to try and impersonate must have an owner
$this->addFlash('danger', 'The user you tried to impersonate has no owner.');
return new RedirectResponse($this->generateUrl('admin_fake_list'));
}
} catch ( \Exception $exception ) {
$this->get('sentry.client')->captureException($exception);
return new RedirectResponse($this->generateUrl('admin_fake_list'));
}
}
/**
* @param EntityManagerInterface $entityManager
* @param TokenStorageInterface $tokenStorage
*
* @param Request $request
* @return RedirectResponse
*/
public function exitImpersonationAction(
EntityManagerInterface $entityManager,
TokenStorageInterface $tokenStorage,
Request $request
)
: RedirectResponse {
try {
/** @var User $user */
$user = $this->getUser();
if ( $user->getIsFake() == false ) {
throw $this->createNotFoundException(
sprintf(
'You are not allowed to do this user #%s.',
$user->getId()
)
);
}
$owner = null;
$currentToken = $tokenStorage->getToken();
$loadedUser = null;
// Check if has the original_impersonator field in token
if ( $currentToken->hasAttribute('original_impersonator') ) {
$userID = $currentToken->getAttribute('original_impersonator');
$loadedUser = $entityManager
->getRepository(User::class)
->findOneBy([ 'id' => $userID ]);
}
if ( !$loadedUser instanceof User ) {
foreach ( $currentToken->getRoles() as $role ) {
if ( $role instanceof SwitchUserRole ) {
/** @var User $owner */
$owner = $role->getSource()->getUser();
}
}
if ( $owner->getId() ) {
/** @var User $loadedUser */
$loadedUser = $entityManager
->getRepository(User::class)
->findOneBy([ 'id' => $owner->getId() ]);
}
}
$token = new UsernamePasswordToken(
$loadedUser, null, 'main',
$loadedUser->getRoles()
); // 'main' is the name of the firewall
$tokenStorage->setToken($token);
$request->getSession()->remove('_switch_user');
$user->setRealIsOnline(false);
$entityManager->persist($user);
$entityManager->flush();
return $this->redirect($this->generateUrl('admin_fake_list'));
} catch ( \Exception $exception ) {
$this->get('sentry.client')->captureException($exception);
return $this->redirect($this->generateUrl('homepage'));
}
}
/**
* @param Request $request
*
* @return string
*/
public function unsubscribeEmailAction(Request $request)
{
$emailingManager = $this->get('social.emailing_manager');
$token = $request->get('token');
$unsubscribed = null;
$submit = $request->get('submit');
if ( $submit == 'true' ) {
$data = $emailingManager->decodeToken($token);
$unsubscribed = false;
if ( is_array($data) ) {
$unsubscribed = $emailingManager->unsubscribeUserByData($data);
}
}
return $this->render(
'SocialFrontendBundle:Account:unsubscribe_email.html.twig',
[
'unsubscribed' => $unsubscribed,
'submit' => $submit,
'url' => 'social_frontend_unsubscribe',
]
);
}
/**
* @param Request $request
*
* @return Response
* @throws OptimisticLockException
*/
public function unsubscribeCampaignEmailAction(Request $request)
{
$contactInviteManager = $this->get('social_internal.contact_inviter_manager');
$token = $request->get('token');
$unsubscribed = null;
$submit = $request->get('submit');
if ( $submit == 'true' ) {
$data = $contactInviteManager->decodeToken($token);
$unsubscribed = false;
if ( is_array($data) ) {
$unsubscribed = $contactInviteManager->unsubscribeUserByData($data);
}
}
return $this->render(
'SocialFrontendBundle:Account:unsubscribe_email.html.twig',
[
'unsubscribed' => $unsubscribed,
'submit' => $submit,
'url' => 'social_email_campaign_unsubscribe',
]
);
}
/**
* @param Request $request
*
* @return Response
*/
public function getPopularUsersForModalNonLoggedInAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$userManager = $this->get('social_user.user_manager');
$viewedUser = null;
if ( $this->getUser() instanceof User ) {
$viewedUser = $this->getUser()->getViewedUser();
} else {
$username = $request->get('username');
$viewedUser = $em->getRepository('SocialUserBundle:User')->findOneByUsername($username);
}
$gender = null;
if ( $viewedUser != null ) {
$gender = $viewedUser->getGender();
}
$profiles = $userManager->findPopularProfilesNearIpAddress(null, null, null, $gender);
return $this->render(
'SocialFrontendBundle:Components/Account:popular_users_for_modal_non_logged_in.html.twig',
[ 'profiles' => $profiles ]
);
}
/**
* @param Request $request
*
* @return JsonResponse|Response
* @throws DBALException
* @throws OptimisticLockException
* @throws Twig_Error
*/
public function inviteAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
if ( $request->getMethod() == 'POST' ) {
$dataCollection = $request->get('emails');
$singleContact = $request->get('single-contact');
$saveableCollection = [];
$nbrSaved = 0;
$totalErrorsFound = 0;
if ( count($dataCollection) ) {
foreach ( $dataCollection as $item ) {
preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $item, $matches);
$name = preg_replace("/\<[^)]+\>/", "", $item);
if ( isset($matches[0][0]) ) {
$saveableCollection[] = [
'email' => $matches[0][0],
'name' => $name,
];
} else {
$totalErrorsFound++;
}
}
/* check how many have been submited in the last 24 hours */
$contactsInvitedInLast24Hours = $this->get(
'social_internal.contact_inviter_manager'
)->getNbrContactsInvitedInLast24Hours($this->getUser());
if ( $this->getParameter('single_contact_invite_max_per_24_hours') > $contactsInvitedInLast24Hours ) {
$nbrSaved = $this->get('social_internal.contact_inviter_manager')->saveImportedContacts(
$this->getUser(),
$saveableCollection,
$singleContact,
true
);
}
}
$response = [];
if ( count($saveableCollection) ) {
$response['import'] = true;
if ( $totalErrorsFound ) {
$response['has_errors'] = true;
} else {
$response['has_errors'] = false;
}
} else {
$response['import'] = false;
}
$response['nbr_saved'] = $nbrSaved;
return new JsonResponse($response);
}
$lastMessage = $em->getRepository('SocialFrontendBundle:Message')->findOneBy(
[
'from_user' => $this->getUser(),
'is_deleted' => 0,
],
[ 'created_at' => 'DESC' ]
);
$lastContact = null;
if ( $lastMessage ) {
$relationship = $lastMessage->getRelationship();
$lastContact = $relationship->getContact($this->getUser());
}
$usersToDisplay = $em->getRepository('SocialUserBundle:User')->findPopularUsersForModalNonLoggedIn(
[ $this->getUser()->getNewLocation() ],
!$this->getUser()->getGender()
);
if ( $lastContact ) {
$usersToDisplay = array_slice($usersToDisplay, 0, 5);
}
$form = $this->createFormBuilder()
->add('submitFile', 'file', [ 'label' => 'File to Submit', 'required' => true ])
->getForm();
return $this->render(
'SocialFrontendBundle:Account:invite.html.twig',
[
'users_to_display' => $usersToDisplay,
'last_contact' => $lastContact,
'form' => $form->createView(),
]
);
}
/**
* @return Response
*/
public function confirmPackageUsageAction(Request $request)
{
return $this->render('SocialFrontendBundle:Account:confirm_package_usage.html.twig');
}
/**
* @param Request $request
*
* @return RedirectResponse
*/
public function acceptPackageUsageAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$user = $this->getUser();
$user->setHasAgreedToWaiveRights(true);
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('social_frontend_account'));
}
/**
* @param Request $request
*
* @return Response
*/
public function channelAuthenticationAction(Request $request)
{
$socketId = $request->get('socket_id');
$em = $this->get('doctrine.orm.entity_manager');
$finalAuth = [];
$pusher = $this->container->get('social.pusher_initializer')->initialize();
$presenceData = [ 'name' => $this->getUser()->getUserName() ];
foreach ( $request->request->get('channel_name') as $roomName ) {
$auth = null;
$status = 200;
$presenceData['id'] = $this->getUser()->getId();
$presenceData['type'] = 'NU'; // Normal User
if ( strpos($roomName, 'presence-room-counter') !== false ) {
$auth = $pusher->presence_auth(
$roomName,
$socketId,
$this->getUser()->getId(),
$presenceData
);
$finalAuth[$roomName] = [
'status' => $status,
'data' => json_decode($auth),
];
return new JsonResponse($finalAuth);
}
if ( strstr($roomName, 'presence-room-call') !== false ) {
$relationshipId = str_replace('presence-room-call-', '', $roomName);
$relationshipIds = $em->getRepository('SocialFrontendBundle:Relationship')->getRelationshipIdsForUser(
$this->getUser()
);
if ( !in_array($relationshipId, $relationshipIds) ) {
// throw $this->createNotFoundException(sprintf('You do not belong to room id(#%s).', $relationshipIds));
$status = 403;
} else {
$presenceData['room_id'] = $relationshipId;
$auth = $pusher->presence_auth(
$roomName,
$socketId,
$this->getUser()->getId(),
$presenceData
);
}
} else {
if ( strstr($roomName, 'presence-room-alerts') !== false ) {
$userId = str_replace('presence-room-alerts-', '', $roomName);
if ( $this->getUser()->getId() == $userId ) {
$auth = $pusher->presence_auth(
$roomName,
$socketId,
$this->getUser()->getId(),
$presenceData
);
} else {
// throw $this->createNotFoundException(sprintf('Could not authenticate channel \'%s\' and socket \'%s\'', $roomName, $socketId));
$status = 403;
}
} else {
if ( strstr($roomName, 'presence-room') !== false ) {
$relationshipId = str_replace('presence-room-', '', $roomName);
$relationshipIds = $em->getRepository(
'SocialFrontendBundle:Relationship'
)->getRelationshipIdsForUser($this->getUser());
if ( !in_array($relationshipId, $relationshipIds) ) {
// throw $this->createNotFoundException(sprintf('You do not belong to room id(#%s).', $relationshipIds));
$status = 403;
} else {
$presenceData['room_id'] = $relationshipId;
$auth = $pusher->presence_auth(
$roomName,
$socketId,
$this->getUser()->getId(),
$presenceData
);
}
} else {
if ( strstr($roomName, 'private-room-call') !== false ) {
$relationshipId = str_replace('private-room-call-', '', $roomName);
$relationshipIds = $em->getRepository(
'SocialFrontendBundle:Relationship'
)->getRelationshipIdsForUser($this->getUser());
if ( !in_array($relationshipId, $relationshipIds) ) {
// throw $this->createNotFoundException(sprintf('You do not belong to room id(#%s).', $relationshipIds));
$status = 403;
} else {
$presenceData['room_id'] = $relationshipId;
$auth = $pusher->presence_auth(
$roomName,
$socketId,
$this->getUser()->getId(),
$presenceData
);
}
} else {
if ( strstr($roomName, 'private-room-alerts') !== false ) {
$userId = str_replace('private-room-alerts-', '', $roomName);
if ( $this->getUser()->getId() == $userId ) {
$auth = $pusher->presence_auth(
$roomName,
$socketId,
$this->getUser()->getId(),
$presenceData
);
} else {
// throw $this->createNotFoundException(sprintf('Could not authenticate channel \'%s\' and socket \'%s\'', $roomName, $socketId));
$status = 403;
}
} else {
if ( strstr($roomName, 'private-room') !== false ) {
$relId = str_replace('private-room-', '', $roomName);
$relationshipIds = $em->getRepository(
'SocialFrontendBundle:Relationship'
)->getRelationshipIdsForUser($this->getUser());
if ( !in_array($relId, $relationshipIds) ) {
// throw $this->createNotFoundException(sprintf('You do not belong to room id(#%s).', $relId));
$status = 403;
} else {
$presenceData['room_id'] = $relId;
$auth = $pusher->presence_auth(
$roomName,
$socketId,
$this->getUser()->getId(),
$presenceData
);
}
} else {
// throw $this->createNotFoundException(sprintf('Could not authenticate channel \'%s\' and socket \'%s\'', $roomName, $socketId));
if ( strstr($roomName, 'private-profile-views-alerts') !== false ) {
$userId = str_replace('private-profile-views-alerts-', '', $roomName);
if ( $this->getUser()->getId() == $userId ) {
$auth = $pusher->presence_auth(
$roomName,
$socketId,
$this->getUser()->getId(),
$presenceData
);
} else {
// throw $this->createNotFoundException(sprintf('Could not authenticate channel \'%s\' and socket \'%s\'', $roomName, $socketId));
$status = 403;
}
} else {
$status = 403;
}
}
}
}
}
}
}
$finalAuth[$roomName] = [
'status' => $status,
'data' => json_decode($auth),
];
}
return new JsonResponse($finalAuth);
}
/**
* @param Request $request
*
* @return JsonResponse|Response
*/
public function pusherWebHookAction(Request $request)
{
file_put_contents(
$this->getParameter('kernel.project_dir') . '/src/Social/FrontendBundle/Controller/text.txt',
$request->getContent()
);
try {
return $this
->get('social.web_hook.channel_event_handler')
->handle(
$_SERVER['HTTP_X_PUSHER_SIGNATURE'],
json_decode($request->getContent(), true)
);
} catch ( Exception $exception ) {
$this->get('sentry.client')->captureException($exception);
}
}
/**
* @param Request $request
*
* @return RedirectResponse
* @throws Twig_Error
*/
public function redirectToCamAction(Request $request)
{
$mailerManager = $this->get('social.mailer');
$mailerManager->sendAdminRedirectToCam($this->getUser());
return $this->redirect($this->getParameter('bonga_cash_redirect_url'));
}
/**
* @param Request $request
*
* @return JsonResponse
*/
public function markTourAsCompletedAction(Request $request)
: JsonResponse {
$em = $this->get('doctrine.orm.entity_manager');
$user = $this->getUser();
$user->setTourCompleted(true);
$em->persist($user);
$em->flush();
return $this->json([]);
}
/**
* @param Request $request
*
* @return RedirectResponse
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*/
public function confirmAccountDeletionAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$userDeletionQueue = new UserDeletionQueue();
$userDeletionQueue->setUserId($this->getUser()->getId());
$userDeletionQueue->setScheduledFor(new DateTime('+13 days'));
$userDeletionQueue->setStatus(UserDeletionQueue::STATUS_NEW);
$userDeletionQueue->setForUser($this->getUser());
$userDeletionQueue->setSource('user_frontend');
$this->getUser()->setReceiveEmailNotifications(0);
/** add him to unsubscribe list */
//$unsubscribeQueue = new UnsubscribeQueue();
//$unsubscribeQueue->setForUser($this->getUser());
//$unsubscribeQueue->setStatus(UnsubscribeQueue::STATUS_NEW);
//$unsubscribeQueue->setScheduledFor(new \DateTime('+10 days'));
//$unsubscribeQueue->setProcessorName('centralPay');
//$em->persist($unsubscribeQueue);
/** @var Payment $userLastPayment */
$userLastPayment = $em->getRepository(Payment::class)
->findOneBy(['from_user' => $this->getUser()], ['id' => 'DESC']);
if ($userLastPayment) {
if ($userLastPayment->getGatewayName() == 'Cardbilling') {
$verotelInstallmentRecord = $em->getRepository(VerotelConfirmationPayment::class)
->findOneBy(['from_user' => $userLastPayment->getFromUser(), 'payment_status' => 'ACCEPTED'], ['id' => 'DESC']);
if ($verotelInstallmentRecord) {
$this->get('social_internal.payments.verotel_card')->cancelSubscription($verotelInstallmentRecord->getSaleID(), 'deleted_front_end', 'Backend');
}
} elseif ($userLastPayment->getGatewayName() == 'centralPay_SF') {
$centralPaySFConfirmationPayment = $em->getRepository(CentralPaySFConfirmationPayment::class)
->find($userLastPayment->getCpsfInstallmentId());
if ($centralPaySFConfirmationPayment) {
$this->get('social_internal.payments.centralpay_provider_v2')->cancelSFPaymentSubscription($this->getUser(), $centralPaySFConfirmationPayment, 'account_deleted', 'frontend');
}
} elseif ($userLastPayment->getGatewayName() == 'CentralPay') {
$this->get('social_internal.payments.centralpay_provider_v2')->cancelCentralPaySubscription($this->getUser());
} else {
$centralPayService = $this->get('social_internal.payments.centralpay_provider_v2')
->processHookRequest(
[
'internalType' => HookUtility::INTERNAL_ACTION_USER_ACCOUNT_DELETE,
'user' => $this->getUser(),
]
);
if ( $centralPayService['error_flag'] == false ) {
$userDeletionQueue->setPaymentReference($centralPayService['merchantTransactionId']);
}
}
}
$em->persist($userDeletionQueue);
$em->persist($this->getUser());
$em->flush();
$this->container->get('security.token_storage')->setToken(null);
return $this->redirect($this->generateUrl('social_user_homepage'));
}
// public function smtpNotificationAction(Request $request)
// {
// $logDir = $this->get('kernel')->getLogDir();
// file_put_contents($logDir . '/' . 'sendinblue.log', serialize($request->request->all()) . "\r\n" . serialize($request->query->all()) . "\r\n -------" . "\r\n", FILE_APPEND);
//
// return new JsonResponse();
// }
public function importSendEmailsAction(Request $request)
{
$emails = $request->get('emails');
$emailsCollection = explode(',', $emails);
$validEmails = [];
$validator = new EmailValidator();
$translator = $this->get('translator');
$contactInviterManager = $this->get('social_internal.contact_inviter_manager');
foreach ( $emailsCollection as $email ) {
$email = trim($email, " \t\n\r\0\x0B,./<>?;:\\\"|[]{}!@#$%^&*()_+-=~`");
if ( $validator->isValid($email, new RFCValidation()) ) {
$validEmails[] = $email;
}
}
$data = [];
foreach ( $validEmails as $validEmail ) {
$data[] = [ 'email' => $validEmail, 'name' => '' ];
}
$contactInviterManager->saveImportedContacts($this->getUser(), $data, false, true);
if ( count($validEmails) ) {
return new JsonResponse([ 'status' => true, 'emails_count' => count($validEmails) ]);
} else {
return new JsonResponse(
[
'status' => false,
'error_message' => $translator->trans('You have not submitted any valid email.'),
]
);
}
}
public function importUploadCsvAction(Request $request)
{
$toolsManager = $this->get('social.tools');
$contactInviterManager = $this->get('social_internal.contact_inviter_manager');
$form = $this->createFormBuilder()
->add(
'submitFile',
'file',
[
'label' => 'File to Submit',
'required' => true,
'constraints' => [
new File(
[
'maxSize' => '1M',
'mimeTypes' => [
'text/csv',
'text/plain',
],
'mimeTypesMessage' => 'Please upload a valid CSV file',
]
),
],
]
)
->getForm();
if ( $request->getMethod() == 'POST' ) {
// Bind request to the form
$form->handleRequest($request);
// If form is valid
if ( $form->isValid() ) {
// Get file
$file = $form->get('submitFile');
// Your csv file here when you hit submit button
$fileData = $file->getData();
$content = $toolsManager->CSVToArray($fileData);
foreach ( $content as $rowNbr => $rowData ) {
if ( isset($rowData['E-mail 1 - Value']) ) {
$email = trim(
$rowData['E-mail 1 - Value'],
" \t\n\r\0\x0B,./<>?;:\\\"|[]{}!@#$%^&*()_+-=~`"
);
$content[$rowNbr]['email'] = $email;
}
if ( isset($rowData['Name']) ) {
$content[$rowNbr]['name'] = $rowData['Name'];
}
}
$contactInviterManager->saveImportedContacts($this->getUser(), $content, false, true);
return $this->redirect($this->generateUrl('social_invite', [ 'csv_upload' => true ]));
} else {
return $this->redirect($this->generateUrl('social_invite', [ 'csv_error' => true ]));
}
}
}
private function getSuggestedFriends()
{
$em = $this->get('doctrine.orm.entity_manager');
$lastFriendSuggestionUpdate = $this->get('session')->get('last_friend_suggestion_update', null);
$friendSuggestionIds = $this->get('session')->get('friend_suggestion_ids', null);
$now = time();
$shouldDoNewFriendSuggestionUpdate = $lastFriendSuggestionUpdate != null ? (($now - $lastFriendSuggestionUpdate) >= 300 ? true : false) : true;
if ( $shouldDoNewFriendSuggestionUpdate ) {
$friendSuggestionIds = $this->get('social.friend_manager')->getFriendSuggestions($this->getUser());
$this->get('session')->set('friend_suggestion_ids', $friendSuggestionIds);
$this->get('session')->set('last_friend_suggestion_update', $now);
}
$friendSuggestions = [];
if (count($friendSuggestionIds)) {
$viewedUser = $this->getUser() ? $this->getUser()->getViewingUser() : null;
if ( !$viewedUser ) {
$ids = array_column(
array_slice(
$friendSuggestionIds,
0,
6
),
'id'
);
} else {
$viewedUserId = $viewedUser->getId();
$position = -1;
foreach ( $friendSuggestionIds as $_pos => $friendSuggestionId ) {
if ( $friendSuggestionId['id'] == $viewedUserId ) {
$position = $_pos;
break;
}
}
$min = $position - 2;
if ( $min < 0 ) {
$min = 0;
}
$beforeAdded = $position - $min;
$max = $position + 3 + (3 - $beforeAdded);
if ( $max > count($friendSuggestionIds) ) {
$max = count($friendSuggestionIds);
}
if ( $max - $min < 6 ) {
/**
* try to move the min
*/
$diff = 6 - ($max - $min);
if ( $min - $diff >= 0 && isset($friendSuggestionIds[$diff - 1]) ) {
$min = $min - $diff;
}
}
$_backupFriendSuggestions = array_slice($friendSuggestionIds, $min, $max - $min);
$ids = array_column(
$_backupFriendSuggestions,
'id'
);
}
$friendSuggestions = $em->getRepository('SocialUserBundle:User')->findBy([ 'id' => $ids ]);
}
return $friendSuggestions;
}
public function getSliderUserListAction()
{
$em = $this->get('doctrine.orm.entity_manager');
$user = $this->getUser() && $this->getUser()->getViewingUser() ? $this->getUser()->getViewingUser() : $this->getUser();
$boostedUsers = $em->getRepository(User::class)->getBoostedUsers([
'current_user' => $user,
'boost_limit' => 4
])->getQuery()->execute();
$friendSuggestions = $this->getSuggestedFriends();
$users = [];
if (count($boostedUsers)) {
$users = array_merge($users, $boostedUsers);
}
if (count($friendSuggestions)) {
$users = array_merge($users, $friendSuggestions);
}
return $this->render(
'SocialFrontendBundle:Components/Friends:friend_suggestion_slider.html.twig', [
'users' => $users
]
);
}
public function boostProfileAction(UserActionManager $userActionManager)
{
$em = $this->getDoctrine()->getManager();
/** @var User $user */
$user = $this->getUser();
/** @var CreditActionsEntity $creditAction */
$creditAction = $em->getRepository(CreditActionsEntity::class)->findOneBy(['code' => CreditActionsEntity::CREDIT_ACTION_BOOST_PROFILE]);
$historyCreditUsage = new CreditUserHistoryEntity();
$historyCreditUsage->setUserId($user);
$historyCreditUsage->setCost($creditAction->getCost());
$historyCreditUsage->setIsFromBonus(false);
$historyCreditUsage->setAction(CreditActionsEntity::CREDIT_ACTION_BOOST_PROFILE);
$historyCreditUsage->setTimestamp(new \DateTime('now'));
$historyCreditUsage->setType(CreditUserHistoryEntity::ACTION_TYPE_SUBTRACT);
$credit = $user->getCredits() - $creditAction->getCost();
$user->setCredits($credit);
$user->setProfileBoosted(true);
$user->setBoostedAt(new \DateTime('now'));
$boostProfileHistory = new UserBoostProfileHistory();
$boostProfileHistory->setUser($user);
$boostProfileHistory->setCreatedAt(new \DateTime('now'));
$boostProfileHistory->setUpdatedAt(new \DateTime('now'));
$em->persist($boostProfileHistory);
$em->persist($historyCreditUsage);
$em->persist($user);
$em->flush();
$validForOpenModal = $userActionManager->validForOpenProfileConfirmationModal($user);
return new JsonResponse(['status' => true, 'message' => 'Boosted Successfully!', 'open_profile_confirmation_modal' => $validForOpenModal]);
}
public function cancelDeletionRequestAction()
{
$em = $this->getDoctrine()->getManager();
/** @var User $user */
$user = $this->getUser();
/** @var UserDeletionQueue $userDeletionQue */
$userDeletionQue = $em->getRepository(UserDeletionQueue::class)->findOneBy(['for_user' => $user, 'isDeleted' => false]);
$userDeletionQue->setIsDeleted(true);
$em->persist($userDeletionQue);
$em->flush();
$this->get('social.alert_manager')->createAlertCancelledDeletionRequest(
$user,
$user
);
return new JsonResponse(['status' => true, 'message' => 'Cancelled Deletion Request Successfully!']);
}
public function bootLiveAction(Request $request)
{
try {
$request->get('_route');
$em = $this->getDoctrine()->getManager();
$bootLiveType = $request->get('action');
if (isset($bootLiveType) && $bootLiveType == 'signup') {
$type = BootProfile::Boot_sign_up;
} else {
$type = BootProfile::Boot_online;
}
$currentUser = $em->getRepository('SocialUserBundle:User')->find($this->getUser()->getId());
$bootLiveProfileList = $em->getRepository('SocialInternalBundle:BootProfile')->findBy(
[
'bootType' => BootProfile::LIVE_ACTION,
'bootLiveType' => $type,
'isActionComplted' => false,
'isDraft' => false,
], ['timeInterval' => 'ASC']);
$toUserList[] = $this->getUser();
for ($i = 0; $i < count($bootLiveProfileList); $i++) {
// $interval = $bootLiveProfileList[$i]->getTimeInterval();
// if ($i > 0) {
// $interval = $bootLiveProfileList[$i]->getTimeInterval() - $bootLiveProfileList[$i-1]->getTimeInterval();
// }
// sleep($interval * 60);
$staffUser = $em->getRepository('SocialUserBundle:User')->find($bootLiveProfileList[$i]->getCreatedBy());
$isUserValidForBoot = $em->getRepository('SocialInternalBundle:EmailList')->findOneBy(
['to_user' => $staffUser, 'signed_up_user' => $currentUser]);
if (isset($isUserValidForBoot)) {
$this->liveAction($bootLiveProfileList[$i], $toUserList);
}
}
return new JsonResponse(['error' => false]);
} catch (Exception $exception) {
return new JsonResponse(['error' => true, 'error_message' => $exception->getMessage()]);
}
}
public function liveAction($bootProfileRecord, $toUserList) {
$bootActionManager = $this->container->get('social_internal.boot_action_manager');
foreach ($bootProfileRecord->getActionString() as $action) {
switch ($action)
{
case 'SEND_MESSAGE':
$actionResult = $bootActionManager->sendMessageAction($bootProfileRecord, $toUserList, true);
break;
case 'VIEW_PROFILE':
$actionResult = $bootActionManager->viewProfileAction($bootProfileRecord, $toUserList, true);
break;
case 'SEND_FRIEND_REQUEST':
$actionResult = $bootActionManager->sendFriendRequestAction($bootProfileRecord, $toUserList, true);
break;
case 'SWIPE':
$actionResult = $bootActionManager->swipeAction($bootProfileRecord, $toUserList, true);
break;
}
}
}
}