<?php
namespace Social\UserBundle\Controller;
use DateTime;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;
use Sentry\ClientInterface;
use Social\CreditsBundle\Entity\CreditUserHistoryEntity;
use Social\FrontendBundle\Service\ConversionManager;
use Social\InternalBundle\Entity\AdminAlertsEntity;
use Social\InternalBundle\Entity\EmailSiteSource;
use Social\InternalBundle\Entity\PackagesList;
use Social\InternalBundle\Entity\SentsioImportHistory;
use Social\InternalBundle\Service\LocationService;
use Social\UserBundle\Form\UserType;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Form\Factory\FactoryInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use FOS\UserBundle\Controller\RegistrationController as BaseRegistrationController;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\FOSUserEvents;
use GuzzleHttp\Client;
use Social\FrontendBundle\Form\NewsletterType;
use Social\InternalBundle\Entity\EmailInviteImport;
use Social\InternalBundle\Entity\EmailList;
use Social\InternalBundle\Entity\TrafficPoll\Conversions;
use Social\InternalBundle\Entity\TrafficPoll\UrlParameters;
use Social\InternalBundle\Entity\TrafficPool;
use Social\UserBundle\Entity\User;
use Social\UserBundle\Entity\UserComponents\UserSignupPollData;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormErrorIterator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* Class RegistrationController
*
* @package Social\UserBundle\Controller
*/
class RegistrationController extends BaseRegistrationController
{
protected $eventDispatcher;
protected $formFactory;
protected $userManager;
protected $tokenStorage;
/** @var LocationService */
private $locationService;
/**
* @var LoggerInterface
*/
private $subscriptionLogger;
/**
* @var ConversionManager
*/
private $conversionManager;
/**
* @var ClientInterface
*/
private $sentry;
public function __construct(
EventDispatcherInterface $eventDispatcher,
FactoryInterface $formFactory,
UserManagerInterface $userManager,
TokenStorageInterface $tokenStorage,
LocationService $locationService,
LoggerInterface $subscriptionLogger,
ConversionManager $conversionManager,
ClientInterface $sentry
) {
$this->eventDispatcher = $eventDispatcher;
$this->formFactory = $formFactory;
$this->userManager = $userManager;
$this->tokenStorage = $tokenStorage;
parent::__construct($eventDispatcher, $formFactory, $userManager, $tokenStorage);
$this->locationService = $locationService;
$this->subscriptionLogger = $subscriptionLogger;
$this->conversionManager = $conversionManager;
$this->sentry = $sentry;
}
/**
* @param Request $request
*
* @return JsonResponse|RedirectResponse|Response|null
* @throws GuzzleException
*/
public function indexAction(Request $request)
{
$userIP = $request->getClientIp();
$locale = $request->getLocale();
$contactEmailList = null; // Inițializare variabilă pentru a evita eroarea "undefined variable"\
try {
if ($this->getUser()) {
if ($this->isGranted('ROLE_SONATA_ADMIN')) {
return $this->redirect($this->get('router')->generate('sonata_admin_dashboard'));
}
return $this->redirect($this->get('router')->generate('social_frontend_search'));
}
/** @var $userManager UserManagerInterface */
$userManager = $this->container->get('fos_user.user_manager');
$socialUserManager = $this->container->get('social_user.user_manager');
/** @var $dispatcher EventDispatcherInterface */
$dispatcher = $this->container->get('event_dispatcher');
$em = $this->getDoctrine()->getManager();
/** @var User $user */
$user = $userManager->createUser();
$user->setEnabled(true); # will rely on confirmed
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $this->createForm(UserType::class, $user, [
'include_birthday' => true,
'include_agree' => true
]);
$form->setData($user);
if ('POST' === $request->getMethod()) {
$user->setEmail('');
$form->handleRequest($request);
$requestParams = $request->get('user');
$email = $requestParams['email'];
$password = $requestParams['password'];
if($password == null || $password == '') {
$form->addError(new FormError($this->get('translator')->trans('A password is required!')));
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$form->addError(new FormError($this->get('translator')->trans('Invalid email')));
}
if ($email !== $requestParams['email_repeat']) {
$form->addError(new FormError($this->get('translator')->trans('Emails are not the same')));
}
if ($form->isValid()) {
try {
$user->setRoles(['ROLE_USER']);
$user->setLastRegistrationStep(4);
$email = $this->replace_spec_char($user->getEmail());
$user->setEmail($email);
$user->setCanCommentOrChat(false);
// Check if user is in email traffic to set if it can comment and send chat message
$emailTrafficUserExists = $this->getDoctrine()->getRepository(EmailList::class)->findOneBy(['email' => $user->getEmail()]);
if ($emailTrafficUserExists instanceof EmailList) {
$user->setCanCommentOrChat(true);
if ($emailTrafficUserExists->getAddedInSentsio()) {
$this->unsubscribeEmailListInSentsio($emailTrafficUserExists);
}
}
$dateTime = new DateTime('now');
$pusherInstanceService = $this->get('social.pusher_initializer')->initialize();
if ($user->hasRole(User::ROLE_USER)) {
$staffUsers = $em->getRepository(User::class)->getStaffUsers();
foreach ($staffUsers as $staffUser) {
if ($staffUser instanceof User) {
$adminAlert = new AdminAlertsEntity();
$adminAlert->setFromUser($user);
$adminAlert->setToUser($staffUser);
$adminAlert->setMessage($user->getUsername() . ' signed up.');
$adminAlert->setType(AdminAlertsEntity::ALERT_TYPE_SIGNUP);
$adminAlert->setIsNew(true);
$adminAlert->setIsRead(false);
$adminAlert->setIsDeleted(false);
$em->persist($adminAlert);
$pusherInstanceService->trigger(
'farmer_notifications_' . $staffUser->getId(),
'farmer_notifications',
[
'id' => $adminAlert->getId(),
'username' => $user->getUsername(),
'to_user' => 'SignUp',
'picture' => '<i class="fas fa-sign-in"></i>',
'action' => 'Sign up',
'type' => 'Sign up',
'message' => 'User ' . $user->getUsername() . 'signed up',
'time' => $dateTime->format('Y-m-d H:i:s'),
'timestamp' => $dateTime->getTimestamp(),
'action_key' => AdminAlertsEntity::ALERT_TYPE_SIGNUP,
'sound' => $this->get('social.alert_manager')->getAlertSoundSetting(AdminAlertsEntity::ALERT_TYPE_SIGNUP, $staffUser)
]
);
}
}
}
$userManager->updateUser($user);
$extendedConfirmationHours = (int)$this->container->getParameter('user_registration_account_activation_time_limit');
$user->setInterestedIn($user->getGender() == 0 ? [1] : [0]);
$user->setExtendPeriodSignupConfirmation((($extendedConfirmationHours > 0) ? $extendedConfirmationHours : 24));
$pinCode = $socialUserManager->generatePinCode();
$user->setPinCode($pinCode);
$em->persist($user);
$em->flush();
$this->subscriptionLogger->info("Created User with ID " . $user->getId());
$localeAdded = false;
$cookies = $request->cookies;
$trafficPollCookies = $cookies->get('tfpr');
$emailLists = [];
// Traffic poll cookies - array
if (isset($trafficPollCookies['pollId'])) {
$pollId = $trafficPollCookies['pollId'];
/** @var TrafficPool $trafficPollEntity */
$trafficPollEntity = $this->getDoctrine()->getRepository(TrafficPool::class)->find($pollId);
$this->subscriptionLogger->info("IN IF with trafficPollEntity = " . $trafficPollEntity->getId());
if ($trafficPollEntity->getId()) {
$this->get('social_internal.boot_action_manager')->createBootLiveSchedule($request, $trafficPollEntity, $user);
if ($trafficPollEntity->getPackageList()) {
$packageName = $trafficPollEntity->getPackageList()->getName();
$credits = $trafficPollEntity->getPackageList()->getCredits();
$user->setPackageName($packageName);
$user->setCredits($credits);
$user->setHasAgreedToWaiveRights(true);
$em->persist($user);
$em->flush();
$this->subscriptionLogger->info("New credits of " . $user->getId() . " is " . $user->getCredits());
$this->addCreditUserHistory($user, $trafficPollEntity->getPackageList());
}
if ($trafficPollEntity->getPollType() == TrafficPool::POLL_TYPE_USER_PAGE ||
$trafficPollEntity->getPollType() == TrafficPool::POLL_TYPE_SEARCH) {
$user->setCanCommentOrChat(true);
$em->persist($user);
$em->flush();
$this->subscriptionLogger->info('pollType = ' . $trafficPollEntity->getPollType());
$contactEmailList = null;
if (!$trafficPollEntity->isAddInEmailList()) {
$contactEmailList = $em->getRepository(EmailList::class)->findOneBy(['email' => $user->getEmail()]);
} else {
$contactEmailList = new EmailList();
$contactEmailList->setEmail($user->getEmail());
$contactEmailList->setSkype(null);
$contactEmailList->setNickname($user->getUsername());
$contactEmailList->setFirstName($user->getFirstName());
$contactEmailList->setLastName($user->getLastName());
$contactEmailList->setEmailLanguage($user->getLanguage());
try {
if ($user->getNewLocation() !== null) {
$contactEmailList->setLocation($user->getNewLocation()->__toString());
} else {
$contactEmailList->setLocation('N/A');
}
} catch (\Exception $exception) {
$contactEmailList->setLocation('N/A2');
$this->sentry->captureException($exception);
}
$contactEmailList->setGender($user->getGender());
$contactEmailList->setMoreDetails('User traffic pool - ' . $trafficPollEntity->getId());
$contactEmailList->setDiscussion('');
$contactEmailList->setUserDificil(false);
if (isset($trafficPollCookies['uts']) && $trafficPollCookies['uts'] !== null && $trafficPollCookies['uts'] > 0) {
$emailSiteSourceEntity = $em->getRepository(EmailSiteSource::class)->find((int)$trafficPollCookies['uts']);
if ($emailSiteSourceEntity instanceof EmailSiteSource) {
$contactEmailList->setEmailSiteSource($emailSiteSourceEntity);
}
}
if (isset($trafficPollCookies['utf']) && $trafficPollCookies['utf'] !== null && $trafficPollCookies['utf'] > 0) {
$toUserId = $em->getRepository(User::class)->find($trafficPollCookies['utf']);
$contactEmailList->setToUser($toUserId);
}
if (isset($trafficPollCookies['uth']) && $trafficPollCookies['uth'] !== null && $trafficPollCookies['uth'] > 0) {
$fromUserId = $em->getRepository(User::class)->find($trafficPollCookies['uth']);
$contactEmailList->setFromUser($fromUserId);
}
// Setting profile sent
$trafficPoolUsers = $trafficPollEntity->getPollUsers();
if ($trafficPoolUsers !== null && count($trafficPoolUsers) === 1) {
$contactEmailList->setProfileSent($trafficPoolUsers[0]);
}
$contactEmailList->setEmailObtainedFromFlag(EmailList::MAIL_OBTAINED_FROM_TRAFFIC_POOL_USER_PAGE);
$em->persist($contactEmailList);
}
if ($contactEmailList) {
$contactEmailList->setSignedUpUser($user);
$em->persist($contactEmailList);
$em->flush();
if ($contactEmailList->getFromUser() && $contactEmailList->getFromUser()->hasRole(User::ROLE_HSTAFF)) {
if ($contactEmailList->getFromUser() instanceof User) {
$adminAlert = new AdminAlertsEntity();
$adminAlert->setFromUser($user);
$adminAlert->setToUser($contactEmailList->getFromUser());
$adminAlert->setMessage($user->getUsername() . ' signed up.');
$adminAlert->setType(AdminAlertsEntity::ALERT_TYPE_SIGNUP);
$adminAlert->setIsNew(true);
$adminAlert->setIsRead(false);
$adminAlert->setIsDeleted(false);
$em->persist($adminAlert);
$em->flush($adminAlert);
$pusherInstanceService->trigger(
'farmer_notifications_' . $contactEmailList->getFromUser()->getId(),
'farmer_notifications',
[
'id' => $adminAlert->getId(),
'username' => $user->getUsername(),
'to_user' => 'SignUp',
'picture' => '<i class="fas fa-sign-in"></i>',
'action' => 'Sign up',
'type' => 'Sign up',
'message' => 'User ' . $user->getUsername() . 'signed up',
'time' => $dateTime->format('Y-m-d H:i:s'),
'timestamp' => $dateTime->getTimestamp(),
'action_key' => AdminAlertsEntity::ALERT_TYPE_SIGNUP,
'sound' => $this->get('social.alert_manager')->getAlertSoundSetting(AdminAlertsEntity::ALERT_TYPE_SIGNUP, $contactEmailList->getFromUser())
]
);
}
}
$emailLists = [$contactEmailList];
}
$source = $trafficPollEntity->getPollType() == TrafficPool::POLL_TYPE_USER_PAGE ? "SignUp UserPage - $pollId" : "SignUp SearchPage - $pollId";
if ($trafficPollEntity->getPackageList()) {
$socialUserManager->addUserPackageHistory($user, $source, $trafficPollEntity->getPackageList(), 'N/A', 0, 0);
}
}
// Getting parameters from traffic poll
$trafficPollParameters = $trafficPollEntity->getUrlParameters();
/** @var UrlParameters $singleParam */
foreach ($trafficPollParameters as $singleParam) {
if (isset($trafficPollCookies[$singleParam->getkeyValue()])) {
$newTrafficTrackData = new UserSignupPollData();
$newTrafficTrackData->setUrlParamReference($singleParam);
$newTrafficTrackData->setPollReference($trafficPollEntity);
$newTrafficTrackData->setLabel($singleParam->getLabel());
$newTrafficTrackData->setUserReference($user);
$newTrafficTrackData->setUrlKey($singleParam->getkeyValue());
$newTrafficTrackData->setDataValue(
$trafficPollCookies[$singleParam->getkeyValue()]
);
$newTrafficTrackData->setCreatedAt(new \DateTime('now'));
$em->persist($newTrafficTrackData);
$em->flush();
}
}
if ($trafficPollEntity->getAutoSetLocation()) {
$this->subscriptionLogger->info('In getAutoSetLocation ');
/* Adding user location if we can */
$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)) {
$user->setNewLocation($userLocation[0]);
$localeAdded = true;
}
}
}
$conversions = $trafficPollEntity->getConversions();
$this->conversionManager->triggerConversionPostbackForLP($trafficPollCookies, $user, $conversions);
if ($localeAdded) {
$this->subscriptionLogger->info('In localeAdded');
}
$historyApiip = $this->locationService->generateLocationHistory($userIP, $user, $trafficPollEntity->getAutoSetLocation());
$this->locationService->postGenerateLocationHistory($historyApiip, $locale);
if ($contactEmailList) {
$contactEmailList->setEmailLanguage($user->getLanguage());
$em->persist($contactEmailList);
$em->flush();
}
}
} else {
$this->subscriptionLogger->info("IN ELSE");
$emailLists = $this->get('social_internal.email_list_manager')->findEmailListsForUser($user);
$packageList = $em->getRepository(PackagesList::class)->findOneBy(['name' => 'default']);
$socialUserManager->addUserPackageHistory($user, 'SignUp Normal', $packageList, 'N/A', 0, 0);
$this->subscriptionLogger->info("credits = " . $packageList->getCredits());
$user->setCredits($packageList->getCredits());
$em->persist($user);
$em->flush();
$this->subscriptionLogger->info("New credits of " . $user->getId() . " is " . $user->getCredits());
$this->addCreditUserHistory($user, $packageList);
/* Adding user location if we can */
$userLocationTrack = $this->get('social_internal.ip_track_manager')->getLocationForIp($userIP);
$userLocation = $this->get('social_internal.ip_track_manager')->getLocationFromDBForUserObject(
$userLocationTrack,
$locale
);
if ($userLocation != null) {
$this->subscriptionLogger->info("userLocation is " . json_encode($userLocation));
if (is_array($userLocation)) {
$this->subscriptionLogger->info("In isArray userLocation is " . $userLocation[0]->getId());
$user->setNewLocation($userLocation[0]);
}
}
$this->subscriptionLogger->info('credit history added for userID ' . $user->getId());
$historyApiip = $this->locationService->generateLocationHistory($userIP, $user, false);
$this->locationService->postGenerateLocationHistory($historyApiip, $locale);
}
$this->subscriptionLogger->info('current credit history for userID ' . $user->getCredits());
$contactInvites = $this->get('social_internal.contact_inviter_manager')->findContactInvitesForUser($user);
/** @var EmailInviteImport $emailImportExists */
$emailImportExists = $em->getRepository('SocialInternalBundle:EmailInviteImport')->findOneBy(['email' => $user->getEmail()]);
$this->subscriptionLogger->info("emailLists = " . count($emailLists));
$this->subscriptionLogger->info("contactInvites = " . count($contactInvites));
if ($emailImportExists) {
$this->subscriptionLogger->info("In emailImportExists");
$emailImportExists->setSignUpMade(true);
$em->persist($emailImportExists);
$em->flush();
$this->get('social.mailer')->sendAdminNewUser($user, $emailLists, $contactInvites, true);
} else {
$this->get('social.mailer')->sendAdminNewUser($user, $emailLists, $contactInvites, false);
}
$em->flush();
$this->triggerSendEmailConfirmationToUser($user, $request);
if ($request->isXmlHttpRequest()) {
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($token);
return new JsonResponse(
[
'error_flag' => false,
'redirectUrl' => $this->generateUrl(
'social_frontend_search',
[],
UrlGeneratorInterface::ABSOLUTE_URL
),
]
);
}
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_check_email');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(
FOSUserEvents::REGISTRATION_COMPLETED,
new FilterUserResponseEvent($user, $request, $response)
);
setcookie('userRegistrationModalFlag', 1);
return $response;
} catch (\Exception $exception) {
$this->sentry->captureException($exception);
return new RedirectResponse($this->generateUrl('social_user_homepage'));
}
}
if ($request->isXmlHttpRequest()) {
$errors = $this->getErrorMessages($form);
$tokenProvider = $this->container->get('security.csrf.token_manager');
$token = $tokenProvider->getToken('example')->getValue();
return new JsonResponse(
[
'error_flag' => true,
'errors' => $errors,
'token' => $token,
]
);
}
}
return $this->container->get('templating')->renderResponse('SocialUserBundle:Registration:index_'.$this->container->get('social.theme_manager')->getActiveTheme()['name'].'.html.twig', [
'form' => $form->createView()
]);
} catch (\Exception $exception) {
$this->sentry->captureException($exception);
return new RedirectResponse($this->generateUrl('social_user_homepage'));
}
}
public function addCreditUserHistory($user, $packageList)
{
$this->subscriptionLogger->info("In addCreditUserHistory");
try {
$em = $this->getDoctrine()->getManager();
if ($this->getParameter('social_credits_mode_activated') == 1) {
$this->subscriptionLogger->info("In addCreditUserHistory social_credits_mode_activated is true");
$historyCredits = new CreditUserHistoryEntity();
$historyCredits->setUserId($user);
$historyCredits->setAction('Convert bonus to credits');
$historyCredits->setType(CreditUserHistoryEntity::ACTION_TYPE_CONVERTO_FROM_BONUS);
$historyCredits->setCost($packageList->getValue());
$historyCredits->setTimestamp(new \DateTime('now'));
$historyCredits->setIsFromBonus(true);
$em->persist($historyCredits);
$em->flush();
}
} catch (\Exception $exception) {
$this->subscriptionLogger->error("error while adding credits to user " . $exception->getMessage());
$this->sentry->captureException($exception);
}
$this->subscriptionLogger->info("completed addCreditUserHistory");
}
public function unsubscribeEmailListInSentsio($emailTrafficUserExists)
{
$em = $this->getDoctrine()->getManager();
$client = HttpClient::create();
$sentSioHistoryData = $em->getRepository(SentsioImportHistory::class)->findBy(['emailList' => $emailTrafficUserExists]);
foreach ($sentSioHistoryData as $sentSioHistory) {
try {
$email = $emailTrafficUserExists->getEmail();
// All EmailLists from sentsio
$existingEmailInSentsio = $client->request('GET', "https://sentsio.com/api/v1/subscribers/email/$email", [
'query' => [
'api_token' => $sentSioHistory->getToken(),
'email' => $email
]
]);
$response = json_decode($existingEmailInSentsio->getContent(), true)['subscribers'];
foreach ($response as $item) {
$uID = $item['uid'];
$listId = $item['list_uid'];
// Update Tag of Subscriber
$client->request('PATCH', "https://sentsio.com/api/v1/subscribers/$uID", [
'query' => [
'api_token' => $sentSioHistory->getToken(),
'uid' => $uID,
'EMAIL' => $email,
'tag' => "email_with_signUp_made"
]
]);
// UNSUBSCRIBE EmailList from Sentsio
$client->request('PATCH', "https://sentsio.com/api/v1/lists/$listId/subscribers/$uID/unsubscribe", [
'query' => [
'api_token' => $sentSioHistory->getToken(),
]
]);
}
} catch (\Exception $exception) {
$this->sentry->captureException($exception);
}
}
return true;
}
private function getErrorMessages(Form $form)
{
$errors = [];
foreach ($form->getErrors() as $error) {
if ($form->isRoot()) {
$errors['#'][] = $error->getMessage();
} else {
$errors[] = $error->getMessage();
}
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors[$child->getName()] = $this->getErrorMessages($child);
}
}
return $errors;
}
/**
* @return Response
*/
public function startDateSectionHomepageAction()
{
return $this->render('SocialUserBundle:Registration:section_start_date_homepage.html.twig');
}
/**
* @return Response
*/
public function ourLoversSectionHomepageAction()
{
return $this->render('SocialUserBundle:Registration:section_our_lovers_homepage.html.twig');
}
/**
* @return Response
*/
public function topMembersSectionHomepageAction()
{
$em = $this->get('doctrine.orm.entity_manager');
$newestUsers = $em->getRepository('SocialUserBundle:User')->findNewestUsers();
$onlineUsers = $em->getRepository('SocialUserBundle:User')->getOnlineUsers();
$popularUsers = $em->getRepository('SocialUserBundle:User')->getPopularUsers();
return $this->render(
'SocialUserBundle:Registration:section_top_members_homepage.html.twig',
['newest_users' => $newestUsers, 'online_users' => $onlineUsers, 'popular_users' => $popularUsers]
);
}
/**
* @return Response
*/
public function testimonialsSectionHomepageAction()
{
return $this->render('SocialUserBundle:Registration:section_testimonials_homepage.html.twig');
}
/**
* @return Response
*/
public function supportSectionHomepageAction()
{
$newsletterForm = $this->createForm(NewsletterType::class, null);
return $this->render(
'SocialUserBundle:Registration:section_support_homepage.html.twig',
['newsletter_form' => $newsletterForm->createView()]
);
}
/**
* @param Request $request
*
* @return RedirectResponse|Response
*/
public function step2Action(Request $request)
{
// If somehow somebody ends here - redirect to account home
return new RedirectResponse($this->generateUrl('social_frontend_homepage_account'));
$translator = $this->get('translator');
$errors = [];
if ($request->getMethod() == 'POST') {
$em = $this->get('doctrine.orm.entity_manager');
$filters = $request->get('filters');
if (count($filters['interest']) == 0) {
return $this->render(
'SocialUserBundle:Registration:step2.html.twig',
['errors' => [$translator->trans('Please choose at least 1 gender you are interested in.')]]
);
}
$user = $this->getUser();
$user->setInterestedIn($filters['interest']);
$this->getUser()->setLastRegistrationStep(2);
$em->persist($this->getUser());
$em->flush();
return $this->redirect($this->generateUrl('social_user_signup_step3'));
}
return $this->render('SocialUserBundle:Registration:step2.html.twig', ['errors' => []]);
}
/**
* @param Request $request
*
* @return RedirectResponse|Response
*/
public function step3Action(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$form = $this->createForm(UserType::class, $this->getUser(), [
'destination' => ['step-3'],
'locale' => $request->getLocale()
]);
if ($request->getMethod() == 'POST') {
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
/** @var User $user */
$user = $form->getData();
if ($user->getImage() && $user->getDeleteProfilePictureId() == $user->getImage()->getId()) {
$user->setImage(null);
}
$user->setIsSetLocationByUser(true);
$user->setLastRegistrationStep(4); // this means that it will skip the invitation step. but we also need to trigger the email sending
if ($user->getNumberLogins() == 0) {
$user->setNumberLogins(1);
}
$em->persist($user);
$em->flush();
if ($user->getNewLocation() !== null) {
setcookie('userRegistrationModalFlag', 0);
}
/** @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() + rand(1, 9999);
$url = $conversion->getUrl();
$url .= '&cb='.$random;
$url .= '&cti='.$user->getId().'-'.$trafficPoll->getCode();
$this->sentry->captureMessage($url);
try {
$response = $client->get($url);
$this->sentry->captureMessage($response->getStatusCode());
} catch (\Exception $exception) {
$this->sentry->captureException($exception);
}
}
}
}
}
}
if ($this->getUser() instanceof User) {
if ($this->getUser()->getNewLocation() !== null) {
setcookie('userRegistrationModalFlag', 0, time() - 3600, '/');
}
}
return $this->json(['error_flag' => false]);
}
return $this->json([
'error_flag' => true,
'data' => $this->recursiveFormErrors(
$form->getErrors(true, false),
[$form->getName()]
),
]);
}
return $this->redirect($this->generateUrl('social_frontend_homepage_account'));
}
private function recursiveFormErrors(FormErrorIterator $formErrors, array $prefixes)
{
$errors = [];
foreach ($formErrors as $formError) {
if ($formError instanceof FormErrorIterator) {
$errors = array_merge(
$errors,
$this->recursiveFormErrors($formError, array_merge($prefixes, [$formError->getForm()->getName()]))
);
} elseif ($formError instanceof FormError) {
$errors[implode('_', $prefixes)][] = $formError->getMessage();
}
}
return $errors;
}
public function registerAction(Request $request)
{
$user = $this->userManager->createUser();
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$event = new FormEvent($form, $request);
$this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$this->userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$this->eventDispatcher->dispatch(
FOSUserEvents::REGISTRATION_COMPLETED,
new FilterUserResponseEvent($user, $request, $response)
);
return $response;
}
$event = new FormEvent($form, $request);
$this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
if (null !== $response = $event->getResponse()) {
return $response;
}
}
return $this->render(
'@FOSUser/Registration/register.html.twig',
[
'form' => $form->createView(),
]
);
}
public function renderPartialProfileConfirmationAction(Request $request)
{
$form = $this->createForm(
UserType::class,
$this->getUser(),
['destination' => ['profile-confirmation'], 'locale' => $request->getLocale()]
);
return $this->render(
'SocialUserBundle:Registration:partial_user_profile_confirmation.html.twig',
['form' => $form->createView()]
);
}
public function stepProfileUpdateAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$form = $this->createForm(UserType::class, $this->getUser(), [
'destination' => ['profile-confirmation'],
'locale' => $request->getLocale()
]);
try {
if ($request->getMethod() == 'POST') {
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
/** @var User $user */
$user = $form->getData();
$user->setLastRegistrationStep(4);
$user->setIsAnon(true);
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('social_frontend_homepage_account'));
}
return $this->json(
[
'error_flag' => true,
'data' => $this->recursiveFormErrors($form->getErrors(true, false), [$form->getName()])
]);
}
} catch (\Exception $exception) {
return $this->json([
'error_flag' => true,
'data' => $this->recursiveFormErrors($form->getErrors(true, false), [$form->getName()]),
]);
}
return $this->redirect($this->generateUrl('social_frontend_homepage_account'));
}
public function renderPartialStep3Action(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$form = $this->createForm(UserType::class, $this->getUser(), [
'destination' => ['step-3'],
'locale' => $request->getLocale()
]);
if ($request->getMethod() == 'POST') {
$form->submit($request);
if ($form->isValid()) {
/** @var User $user */
$user = $form->getData();
if ($user->getImage() && $user->getDeleteProfilePictureId() == $user->getImage()->getId()) {
$user->setImage(null);
}
$user->setLastRegistrationStep(4); // this means that it will skip the invitation step. but we also need to trigger the email sending
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('social_frontend_homepage_account'));
}
}
return $this->render(
'SocialUserBundle:Registration:partial_step3.html.twig',
['form' => $form->createView()]
);
}
public function renderSetPasswordAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$form = $this->createForm(
UserType::class,
$this->getUser(),
['destination' => ['set-password'], 'locale' => $request->getLocale()]
);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$user = $form->getData();
$this->userManager->updateUser($user);
$em->persist($user);
$em->flush();
return $this->json(['error_flag' => false]);
}
return $this->json(
[
'error_flag' => true,
'data' => $this->recursiveFormErrors(
$form->getErrors(true, false),
[$form->getName()]
),
]
);
}
return $this->render(
'SocialUserBundle:Registration:partial_user_set_password.html.twig',
['form' => $form->createView()]
);
}
/**
* @param Request $request
*
* @return RedirectResponse|Response
*/
public function step4Action(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
if ($request->getMethod() == 'POST') {
$user = $this->getUser();
$user->setLastRegistrationStep(4);
$em->persist($user);
$em->flush();
$this->triggerSendEmailConfirmationToUser($user, $request);
$em->persist($user);
$em->flush();
return $this->redirect($this->get('router')->generate('fos_user_registration_check_email'));
}
return $this->render('SocialUserBundle:Registration:step4.html.twig');
}
/**
* @param Request $request
*
* @return RedirectResponse|Response|null
*/
public function checkEmailAction(Request $request)
{
$user = $this->getUser();
if ($user) {
if ($this->getUser()->isProfileCompleted()) {
return $this->redirect($this->generateUrl('social_frontend_search'));
} else {
return $this->render(
'@SocialUser/Registration/checkEmail.html.twig',
[
'user' => $this->getUser(),
]
);
}
}
}
/**
* @param Request $request
* @param TranslatorInterface $translator
* @param EntityManagerInterface $entityManager
*
* @return RedirectResponse
*/
public function resendConfirmationEmailAction(
Request $request,
TranslatorInterface $translator,
EntityManagerInterface $entityManager
) {
try {
$em = $entityManager;
$this->get('session')->getFlashBag()->add(
'notice',
$translator->trans('The confirmation email was successfully sent to your email address!')
);
/** @var User $user */
$user = $this->getUser();
$this->triggerSendEmailConfirmationToUser($user, $request);
$em->persist($user);
$em->flush();
return $this->redirect($this->get('router')->generate('fos_user_registration_check_email'));
} catch (\Exception $exception) {
$this->sentry->captureException($exception);
}
}
/**
* @param Request $request
* @param string $token
*
* @return null|RedirectResponse|Response
*/
public function confirmAction(Request $request, $token)
{
/** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** @var User|null $user */
$user = $userManager->findUserByConfirmationToken($token);
if (null === $user) {
return $this->redirect($this->generateUrl('social_frontend_homepage_account'));
}
if ($user->isEnabled() == false) {
// throw new NotFoundHttpException(sprintf('The user #%s - %s is marked as disabled. It cannot be confirmed.', $user->getId(), $user));
return $this->redirect($this->generateUrl('social_user_homepage'));
}
/** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user->setConfirmationToken(null);
// $user->setEnabled(true);
$user->setConfirmed(true);
if ($user->isProfileCompleted()) {
$this->get('social.mailer')->sendAccountConfirmedEmail($user);
}
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('social_frontend_homepage_account');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(
FOSUserEvents::REGISTRATION_CONFIRMED,
new FilterUserResponseEvent($user, $request, $response)
);
$this->get('social_user.user_authentication_handler')->main($user);
return $response;
}
/**
* @param User $user
* @param Request $request
*/
private function triggerSendEmailConfirmationToUser(User $user, Request $request)
{
$dispatcher = $this->container->get('event_dispatcher');
$form = $this->createForm(UserType::class, $user);
//$formFactory = $this->container->get('fos_user.registration.form.factory');
//$form = $formFactory->createForm();
//$form->setData($user);
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
}
private function replace_spec_char($subject)
{
$char_map = [
"ъ" => "-",
"ь" => "-",
"Ъ" => "-",
"Ь" => "-",
"А" => "A",
"Ă" => "A",
"Ǎ" => "A",
"Ą" => "A",
"À" => "A",
"Ã" => "A",
"Á" => "A",
"Æ" => "A",
"Â" => "A",
"Å" => "A",
"Ǻ" => "A",
"Ā" => "A",
"א" => "A",
"Б" => "B",
"ב" => "B",
"Þ" => "B",
"Ĉ" => "C",
"Ć" => "C",
"Ç" => "C",
"Ц" => "C",
"צ" => "C",
"Ċ" => "C",
"Č" => "C",
"©" => "C",
"ץ" => "C",
"Д" => "D",
"Ď" => "D",
"Đ" => "D",
"ד" => "D",
"Ð" => "D",
"È" => "E",
"Ę" => "E",
"É" => "E",
"Ë" => "E",
"Ê" => "E",
"Е" => "E",
"Ē" => "E",
"Ė" => "E",
"Ě" => "E",
"Ĕ" => "E",
"Є" => "E",
"Ə" => "E",
"ע" => "E",
"Ф" => "F",
"Ƒ" => "F",
"Ğ" => "G",
"Ġ" => "G",
"Ģ" => "G",
"Ĝ" => "G",
"Г" => "G",
"ג" => "G",
"Ґ" => "G",
"ח" => "H",
"Ħ" => "H",
"Х" => "H",
"Ĥ" => "H",
"ה" => "H",
"I" => "I",
"Ï" => "I",
"Î" => "I",
"Í" => "I",
"Ì" => "I",
"Į" => "I",
"Ĭ" => "I",
"И" => "I",
"Ĩ" => "I",
"Ǐ" => "I",
"י" => "I",
"Ї" => "I",
"Ī" => "I",
"І" => "I",
"Й" => "J",
"Ĵ" => "J",
"ĸ" => "K",
"כ" => "K",
"Ķ" => "K",
"К" => "K",
"ך" => "K",
"Ł" => "L",
"Ŀ" => "L",
"Л" => "L",
"Ļ" => "L",
"Ĺ" => "L",
"Ľ" => "L",
"ל" => "L",
"מ" => "M",
"М" => "M",
"ם" => "M",
"Ñ" => "N",
"Ń" => "N",
"Н" => "N",
"Ņ" => "N",
"ן" => "N",
"Ŋ" => "N",
"נ" => "N",
"ʼn" => "N",
"Ň" => "N",
"Ø" => "O",
"Ó" => "O",
"Ò" => "O",
"Ô" => "O",
"Õ" => "O",
"О" => "O",
"Ő" => "O",
"Ŏ" => "O",
"Ō" => "O",
"Ǿ" => "O",
"Ǒ" => "O",
"Ơ" => "O",
"פ" => "P",
"ף" => "P",
"П" => "P",
"ק" => "Q",
"Ŕ" => "R",
"Ř" => "R",
"Ŗ" => "R",
"ר" => "R",
"Р" => "R",
"®" => "R",
"Ş" => "S",
"Ś" => "S",
"Ș" => "S",
"Š" => "S",
"С" => "S",
"Ŝ" => "S",
"ס" => "S",
"Т" => "T",
"Ț" => "T",
"ט" => "T",
"Ŧ" => "T",
"ת" => "T",
"Ť" => "T",
"Ţ" => "T",
"Ù" => "U",
"Û" => "U",
"Ú" => "U",
"Ū" => "U",
"У" => "U",
"Ũ" => "U",
"Ư" => "U",
"Ǔ" => "U",
"Ų" => "U",
"Ŭ" => "U",
"Ů" => "U",
"Ű" => "U",
"Ǖ" => "U",
"Ǜ" => "U",
"Ǚ" => "U",
"Ǘ" => "U",
"В" => "V",
"ו" => "V",
"Ý" => "Y",
"Ы" => "Y",
"Ŷ" => "Y",
"Ÿ" => "Y",
"Ź" => "Z",
"Ž" => "Z",
"Ż" => "Z",
"З" => "Z",
"ז" => "Z",
"а" => "a",
"ă" => "a",
"ǎ" => "a",
"ą" => "a",
"à" => "a",
"ã" => "a",
"á" => "a",
"æ" => "a",
"â" => "a",
"å" => "a",
"ǻ" => "a",
"ā" => "a",
'A¡' => 'a',
"б" => "b",
"þ" => "b",
"ĉ" => "c",
"ć" => "c",
"ç" => "c",
"ц" => "c",
"ċ" => "c",
"č" => "c",
"Ч" => "ch",
"ч" => "ch",
"д" => "d",
"ď" => "d",
"đ" => "d",
"ð" => "d",
"è" => "e",
"ę" => "e",
"é" => "e",
"ë" => "e",
"ê" => "e",
"е" => "e",
"ē" => "e",
"ė" => "e",
"ě" => "e",
"ĕ" => "e",
"є" => "e",
"ə" => "e",
"ф" => "f",
"ƒ" => "f",
"ğ" => "g",
"ġ" => "g",
"ģ" => "g",
"ĝ" => "g",
"г" => "g",
"ґ" => "g",
"ħ" => "h",
"х" => "h",
"ĥ" => "h",
"i" => "i",
"ï" => "i",
"î" => "i",
"í" => "i",
"ì" => "i",
"į" => "i",
"ĭ" => "i",
"ı" => "i",
"и" => "i",
"ĩ" => "i",
"ǐ" => "i",
"ї" => "i",
"ī" => "i",
"і" => "i",
"й" => "j",
"ĵ" => "j",
"ķ" => "k",
"к" => "k",
"ł" => "l",
"ŀ" => "l",
"л" => "l",
"ļ" => "l",
"ĺ" => "l",
"ľ" => "l",
"м" => "m",
"ñ" => "n",
"ń" => "n",
"н" => "n",
"ņ" => "n",
"ŋ" => "n",
"ň" => "n",
"ø" => "o",
"ó" => "o",
"ò" => "o",
"ô" => "o",
"õ" => "o",
"о" => "o",
"ő" => "o",
"ŏ" => "o",
"ō" => "o",
"ǿ" => "o",
"ǒ" => "o",
"ơ" => "o",
"п" => "p",
"ŕ" => "r",
"ř" => "r",
"ŗ" => "r",
"р" => "r",
"ş" => "s",
"ś" => "s",
"ș" => "s",
"š" => "s",
"с" => "s",
"ŝ" => "s",
"т" => "t",
"ț" => "t",
"ŧ" => "t",
"ť" => "t",
"ţ" => "t",
"ù" => "u",
"û" => "u",
"ú" => "u",
"ū" => "u",
"у" => "u",
"ũ" => "u",
"ư" => "u",
"ǔ" => "u",
"ų" => "u",
"ŭ" => "u",
"ů" => "u",
"ű" => "u",
"ǖ" => "u",
"ǜ" => "u",
"ǚ" => "u",
"ǘ" => "u",
"в" => "v",
"ý" => "y",
"ы" => "y",
"ŷ" => "y",
"ÿ" => "y",
"ź" => "z",
"ž" => "z",
"ż" => "z",
"з" => "z",
"ſ" => "z",
"™" => "tm",
"Ä" => "ae",
"Ǽ" => "ae",
"ä" => "ae",
"ǽ" => "ae",
"ij" => "ij",
"IJ" => "ij",
"я" => "ja",
"Я" => "ja",
"Э" => "je",
"э" => "je",
"ё" => "jo",
"Ё" => "jo",
"ю" => "ju",
"Ю" => "ju",
"œ" => "oe",
"Œ" => "oe",
"ö" => "oe",
"Ö" => "oe",
"щ" => "sch",
"Щ" => "sch",
"ш" => "sh",
"Ш" => "sh",
"ß" => "ss",
"Ü" => "ue",
"Ж" => "zh",
"ж" => "zh",
];
return strtr($subject, $char_map);
}
}