<?php
namespace Social\FrontendBundle\Controller;
use DateTime;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
use Exception;
use Social\InternalBundle\Entity\EmailListValidationHistory;
use Social\UserBundle\Form\UserType;
use Sentry\Client;
use Social\InternalBundle\Entity\TrafficPoll\CommercialCards;
use Social\InternalBundle\Entity\TrafficPool;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Class SearchController
*
* @package Social\FrontendBundle\Controller
*/
class SearchController extends Controller
{
/**
* @return Response
*/
public function indexAction()
{
$form = $this->createForm(UserType::class, null, [
'include_birthday' => true,
'include_agree' => true,
]);
return $this->render('SocialFrontendBundle:Search:index.html.twig', ['form' => $form->createView()]);
}
public function trafficPoolAction(Request $request)
{
try {
if ($this->getUser() !== null && $this->getUser()->getId()) {
return $this->redirectToRoute('social_frontend_homepage_account');
}
$trafficReffId = $request->get('trafficIdRef');
$currentPage = $request->get('page');
/** @var TrafficPool $pollEntity */
$pollEntity = $this->getDoctrine()->getRepository(TrafficPool::class)
->findOneBy(['code' => $trafficReffId]);
if ($pollEntity) {
if (!$pollEntity->isActive()) {
return $this->redirectToRoute('social_frontend_search');
}
$now = new DateTime('now');
if ($pollEntity->getActiveUntil() != null && $pollEntity->getActiveUntil() instanceof DateTime) {
if ($pollEntity->getActiveUntil() < $now) {
return $this->redirectToRoute('social_frontend_search');
}
}
$filters['limit'] = 12;
$filters['page'] = $currentPage;
$filters['offset'] = ($filters['page'] - 1) * $filters['limit'];
$filters['poll'] = $pollEntity->getId();
$qb = $this->getDoctrine()->getRepository('SocialUserBundle:User')->getQueryBuilderForUserInPoolsByFilters($filters);
$users = $qb->getQuery()->execute();
$commercials = $pollEntity->getCommercialCards();
$hasCommercials = count($commercials) > 0 ? true : false;
$remadeUsers = [];
if ($hasCommercials) {
/** @var CommercialCards $singleCommercial */
foreach ($commercials as $singleCommercial) {
if ($singleCommercial->getPositions() != null && $singleCommercial->getPositions() != '') {
if ($singleCommercial->getActive() == true) {
if ($singleCommercial->getActiveUntil() != null && $singleCommercial->getActiveUntil() instanceof DateTime) {
if ($singleCommercial->getActiveUntil() >= $now) {
$remadeUsers[($singleCommercial->getPositions() - 1)] = $singleCommercial;
}
} else {
$remadeUsers[($singleCommercial->getPositions() - 1)] = $singleCommercial;
}
}
}
}
}
$lastPosition = 0;
$countUsers = count($users);
for ($i = 0; $i < $countUsers; $i++) {
if (isset($remadeUsers[$i]) && !empty($remadeUsers[$i])) {
// Check next until we have a slot available
for ($j = $i; $j < count($users) + count($commercials) + 1; $j++) {
if (!isset($remadeUsers[$j]) || empty($remadeUsers[$j])) {
$lastPosition = $j;
$remadeUsers[$lastPosition] = $users[$i];
break;
}
}
} else {
$lastPosition = $i;
$remadeUsers[$lastPosition] = $users[$i];
}
}
ksort($remadeUsers);
$renderedUsers = $this->renderView('SocialFrontendBundle:Search:submit.html.twig',
['users' => $remadeUsers, 'trafficPollFlag' => true, 'page' => $currentPage]);
$options = [
'currentPage' => $filters['page'],
'total' => 5,
'lastPage' => 5,
];
$formObject= $this->createForm(UserType::class,null,[
'include_birthday'=> true,
'include_agree' => true
]);
//$formFactory = $this->container->get('fos_user.registration.form.factory');
//$form = $formFactory->createForm(['include_birthday' => true, 'include_agree' => true]);
$form = $formObject->createView();
$response = $this->render('SocialFrontendBundle:Search:search_traffic_poll.html.twig', [
'trafficID' => $trafficReffId,
'renderedUsers' => $renderedUsers,
'trafficPoll' => $pollEntity,
'form' => $form,
'pagination' => $this->renderView(
'SocialFrontendBundle:Components:pagination.html.twig',
[
'filters' => [],
'options' => $options,
'routeName' => 'social_frontend_search_submit',
'sort' => null,
'sort_type' => null,
]
),
]);
$urlParams = $pollEntity->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]', $pollEntity->getId(), 0, '/', null, false, false);
$response->headers->setCookie($cookie);
return $response;
} else {
return $this->redirectToRoute('social_frontend_homepage_account');
}
} catch (Exception $exception) {
/** @var Client $sentry */
$sentry = $this->get('sentry.client');
$sentry->captureException($exception);
return $this->redirectToRoute('social_frontend_homepage_account');
}
}
public function addToSentry($exception)
{
/** @var Client $sentry */
$sentry = $this->get('sentry.client');
$sentry->captureException($exception);
return $this->redirectToRoute('social_frontend_search');
}
/**
* @param Request $request
*
* @return JsonResponse|Response
*/
public function submitAction(Request $request)
{
$pageLimit = 12;
$em = $this->get('doctrine.orm.entity_manager');
$filters = $request->get('filters');
$currentPage = !$this->getUser() ? 1 : $request->get('page', 1);
$filters['current_user'] = $this->getUser();
$filters['frontend_search_mode'] = true;
$filters['loop'] = $request->get('loop') ?: 0;
if ($this->getUser()) {
$filters['gender'] = $this->getUser()->getInterestedIn();
}
$filters['default_member_profile_username'] = $this->getParameter('default_member_profile')['username'];
$filters['page'] = $currentPage;
$filters['boost_limit'] = 3;
$filters['boost_offset'] = ($filters['page'] - 1) * $filters['boost_limit'];
$withoutBoosted = !(isset($filters['boost_profiles']) && $filters['boost_profiles'] === 'on');
$boostedUsers = (isset($filters['loop']) && $filters['loop'] == 0) ? $em->getRepository('SocialUserBundle:User')->getBoostedUsers($filters)->getQuery()->execute() : [];
$filters['limit'] = $pageLimit - count($boostedUsers); //($this->getUser() && $this->getUser()->canDisplayCamsLink()) ? 10 : 12;
$filters['offset'] = ($filters['page'] - 1) * $filters['limit'];
$qbUsers = $em->getRepository('SocialUserBundle:User')->getQueryBuilderByFilters($filters, null, true, $withoutBoosted)->getQuery()->execute();
$total = count($qbUsers);
// if (isset($filters['loop']) && $filters['loop'] == 1) {
// $allUsersFilter = $filters;
// $allUsersFilter['allUsers'] = true;
// $allUsers = $em->getRepository('SocialUserBundle:User')->getQueryBuilderByFilters($allUsersFilter, null, true, true)->getQuery()->execute();
// $qbUsers = $allUsers;
// }
shuffle($qbUsers);
$users = array_merge($boostedUsers, $qbUsers);
$totalPages = ceil($total / $pageLimit);
if ($request->isXmlHttpRequest()) {
return new JsonResponse(
[
'html' => $this->renderView(
'SocialFrontendBundle:Search:submit.html.twig',
['users' => $users, 'page' => $currentPage, 'isInLoop' => isset($filters['loop']) && $filters['loop'] ? $filters['loop'] : 0]
),
'lastPage' => $totalPages,
]
);
} else {
return $this->render('SocialFrontendBundle:Search:index.html.twig');
}
}
public function checkEmailInNeverbounceAction(Request $request)
{
try {
$em = $this->getDoctrine()->getManager();
$email = $request->get('email');
$result = [];
if ($email) {
$validator = new EmailValidator();
if ($validator->isValid($email, new RFCValidation())) {
$isExistInHistory = $em->getRepository(EmailListValidationHistory::class)->findOneBy(['email' => $email]);
if (!$isExistInHistory) {
$client = HttpClient::create();
$apiKey = $_ENV['NEVERBOUNCE_API_KEY'];
$response = $client->request('GET', 'https://api.neverbounce.com/v4/single/check', [
'query' => [
'key' => $apiKey,
'email' => $email
],
]);
$result = json_decode($response->getContent(), true);
$emailListValidationHistory = new EmailListValidationHistory();
$emailListValidationHistory->setEmail($email);
$emailListValidationHistory->setStatus($result['result']);
$em->persist($emailListValidationHistory);
$em->flush();
} else {
$result['result'] = $isExistInHistory->getStatus();
}
} else {
$result['result'] = 'invalid';
}
}
return new JsonResponse(['result' => $result['result']]);
} catch (\Exception $exception) {
$this->get('sentry.client')->captureMessage($exception);
}
}
}