src/Aviatur/GeneralBundle/Controller/GeneralController.php line 87

Open in your IDE?
  1. <?php
  2. namespace Aviatur\GeneralBundle\Controller;
  3. use Aviatur\FlightBundle\Entity\AdminFeeWhitemark;
  4. use Aviatur\FlightBundle\Services\SearchFlightCookie;
  5. use Aviatur\FormBundle\Entity\Newsletter;
  6. use Aviatur\GeneralBundle\Entity\Alerts;
  7. use Aviatur\GeneralBundle\Entity\Whitemark;
  8. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  9. use Aviatur\GeneralBundle\Services\AviaturPixeles;
  10. use Aviatur\GeneralBundle\Services\AviaturUpdatePromoProduct;
  11. use Aviatur\TwigBundle\Services\TwigFolder;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  14. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  15. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  19. use Doctrine\Persistence\ManagerRegistry;
  20. use Aviatur\GeneralBundle\Services\AviaturLogSave;
  21. class GeneralController extends AbstractController
  22. {
  23.     public function indexAction(Request $requestManagerRegistry $registrySessionInterface $sessionSearchFlightCookie $searchFlightCookieAviaturUpdatePromoProduct $aviaturUpdatePromoProductTwigFolder $twigFolderAviaturPixeles $aviaturPixeles)
  24.     {
  25.         $cookieLastSearch $searchFlightCookie->searchFlightCookie();
  26.         $agencyId $session->get('agencyId');
  27.         $em $registry->getManager();
  28.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($agencyId);
  29.         // Agregar link de redireccion para iniciar sesión en portal de aval
  30.         $link_portal_aval $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_aval_redirection');
  31.         $config_links_aval json_decode($link_portal_aval->getValue());
  32.         $redirect_to_aval = !empty($link_portal_aval) ? $config_links_aval->Config->links->logo '' ;
  33.         $login_aval = !empty($link_portal_aval) ? $config_links_aval->Config->links->login '' ;
  34.         $session->set('link_portal_aval'$redirect_to_aval);
  35.         $session->set('login_portal_aval'$login_aval);
  36.         $promoType 'main';
  37.         $promoTypeBanners 'main-banners';
  38.         $promoTypeEscapadas 'main-escapadas';
  39.         $promoTypeExperiencias 'main-experiencias';
  40.         $promoTypeRecommendations 'main-recommendations';
  41.         $blackFridayDate $em->createQuery('SELECT a,b FROM AviaturEditionBundle:HomePromoTime a  JOIN a.homePromoList b WHERE b.type = :promo');
  42.         $blackFridayDateInfo $blackFridayDate->setParameter('promo''black-friday-col')->getResult();
  43.         $activeBlackFriday false;
  44.         if ((is_countable($blackFridayDateInfo) ? count($blackFridayDateInfo) : 0) > 0) {
  45.             $date_start strtotime(date($blackFridayDateInfo[0]->getStartDate()->format('Y-m-d H:i:s')));
  46.             $date_end strtotime(date($blackFridayDateInfo[0]->getEndDate()->format('Y-m-d H:i:s')));
  47.             $date_now strtotime(date('Y-m-d H:i:s'));
  48.             if ($date_start <= $date_now && $date_end >= $date_now) {
  49.                 $activeBlackFriday true;
  50.             }
  51.         }
  52.         $active_background_home = ['active' => false];
  53.         $parametername 'aviatur_background_home_image';
  54.         $background_home_query $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName($parametername);
  55.         if ((is_countable($background_home_query) ? count($background_home_query) : 0) > 0) {
  56.             $backgroundinfo json_decode($background_home_query->getDescription());
  57.             $arrayinfo = [];
  58.             foreach ($backgroundinfo as $key => $info) {
  59.                 if ((int) $key == (int) $agencyId) {
  60.                     foreach ($info as $i) {
  61.                         if ('' == $i->date_end) {
  62.                             if (strtotime(date($i->date_start)) <= $date_now && 'true' == $i->active) {
  63.                                 $arrayinfo $i;
  64.                             }
  65.                         } else {
  66.                             if (strtotime(date($i->date_start)) <= $date_now && strtotime(date($i->date_end)) >= $date_now && 'true' == $i->active) {
  67.                                 $active_background_home = ['active' => true'name' => $i->img'type' => $i->type];
  68.                             }
  69.                         }
  70.                     }
  71.                 }
  72.             }
  73.             if (false == $active_background_home['active']) {
  74.                 if ((is_countable($arrayinfo) ? count($arrayinfo) : 0) > 0) {
  75.                     $active_background_home = ['active' => true'name' => $arrayinfo->img'type' => $arrayinfo->type];
  76.                 }
  77.             }
  78.         }
  79.         $promoSearchAgency $aviaturUpdatePromoProduct->promoSearchAgency($agencyId);
  80.         if (true === $session->has('whitemark')) {
  81.             $promoType $promoType.'_'.$session->get('whitemark');
  82.         }
  83.         $info $this->getOS($request);
  84.         $em $registry->getManager();
  85.         $parameter $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneBy(['name' => 'agency_excluded_list_promotional_cards']);
  86.         if ($parameter) {
  87.             // Decodificar el JSON a un array PHP
  88.             $agenciesExcluded json_decode($parameter->getValue(), true);
  89.             // Verificar si la decodificación fue exitosa
  90.             if (!is_array($agenciesExcluded)) {
  91.                 // Manejar el error si la decodificación no es un array
  92.                 throw new \Exception('La lista de agencias excluidas no es válida.');
  93.             }
  94.         } else {
  95.             // Si no existe el parámetro, usar la lista estática como fallback
  96.             $agenciesExcluded = [
  97.                 'Aviatur S.A.S.''Aviatur S.A.S. Metasearch''QA Aval''Aval''Aviacaribbean''Aviatur - WorldPay''Aviatur Carnaval BAQ MB''Aviatur Colombia''Aviatur Colombia EN',
  98.                 'Aviatur Colombia ES''Aviatur Ecoturismo''Aviatur Kioskos''Aviatur Metasearch Mexico''Aviatur Mexico''Aviatur Mexico QA''Aviatur Mobile''Aviatur PinBus',
  99.                 'Aviatur - Pruebas''BabyMarket''Buceo Colombia''Cielos Abiertos''Corona Aviatur''Directo a la Playa''Experiencias Jet-Set''Great Vibes''Landing visa',
  100.                 'Lufthansa City Center''Megatours''Octopus Agents''Octopus Marcas Blancas''Octopus Travel QA''Panturismo Marcas Blancas''Parque Tayrona''Representaciones Pasabordo WM',
  101.                 'Rokatur Marcas Blancas''RollingTrips''Star World''Swissandina''Takentours''TerraNet Marcas Blancas''Turiscol Ltda.''Aviatur S.A.''Union de Representaciones',
  102.                 'Union de Representaciones - Whitemark''Virtuoso''Claro''WeCare''Octopus Travel Ltda.''Aviatur Site''Aviatur S.A.S. - BBVA''Aviatur Welcome Beds''JTR Aviatur''QA.pruebaAviatur S.A.S.',
  103.             ];
  104.         }
  105.         $agencyPromoId 172;
  106.         $validationAgencyFolder false;
  107.         foreach ($agenciesExcluded as $agencyExcluded) {
  108.             if ($agencyExcluded === $agency->getName()) {
  109.                 $agencyPromoId $agency->getId();
  110.                 $validationAgencyFolder true;
  111.             }
  112.         }
  113.         $homePromoList $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromoList::class)->findOneBy(['type' => $promoType'agency' => $agencyPromoId]);
  114.         if (null != $homePromoList) {
  115.             $homePromoTitle $homePromoList->getTitle();
  116.             $homePromoSubtitle $homePromoList->getSubtitle();
  117.             $homePromos $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromo::class)->findByHomePromoList($homePromoList, ['date' => 'DESC']);
  118.         } else {
  119.             $homePromoTitle null;
  120.             $homePromoSubtitle null;
  121.             $homePromos = [];
  122.         }
  123.         if (null != $homePromos) {
  124.             $linkSwitchPromos = [];
  125.             foreach ($homePromos as $homePromo) {
  126.                 if ('banner' == $homePromo->getSize() && $homePromo->getSwitch()) {
  127.                     $linkSwitchPromos[] = $homePromo;
  128.                 }
  129.             }
  130.         } else {
  131.             $linkSwitchPromos = [];
  132.         }
  133.         $homePromoListBanners $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromoList::class)->findOneBy(['type' => $promoTypeBanners'agency' => $agencyPromoId]);
  134.         if (null != $homePromoListBanners) {
  135.             $homePromoBannersTitle $homePromoListBanners->getTitle();
  136.             $homePromoBannersSubtitle $homePromoListBanners->getSubtitle();
  137.             $homePromosBanners $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromo::class)->findByHomePromoList($homePromoListBanners, ['date' => 'DESC']);
  138.         } else {
  139.             $homePromoBannersTitle null;
  140.             $homePromoBannersSubtitle null;
  141.             $homePromosBanners = [];
  142.         }
  143.         $homePromoListEscapadas $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromoList::class)->findOneBy(['type' => $promoTypeEscapadas'agency' => $agencyPromoId]);
  144.         if (null != $homePromoListEscapadas) {
  145.             $homePromoEscapadasTitle $homePromoListEscapadas->getTitle();
  146.             $homePromoEscapadasSubtitle $homePromoListEscapadas->getSubtitle();
  147.             $homePromosEscapadas $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromo::class)->findByHomePromoList($homePromoListEscapadas, ['date' => 'DESC']);
  148.         } else {
  149.             $homePromoEscapadasTitle null;
  150.             $homePromoEscapadasSubtitle null;
  151.             $homePromosEscapadas = [];
  152.         }
  153.         $homePromoListExperiencias $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromoList::class)->findOneBy(['type' => $promoTypeExperiencias'agency' => $agencyPromoId]);
  154.         if (null != $homePromoListExperiencias) {
  155.             $homePromoExperienciasTitle $homePromoListExperiencias->getTitle();
  156.             $homePromoExperienciasSubtitle $homePromoListExperiencias->getSubtitle();
  157.             $homePromosExperiencias $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromo::class)->findByHomePromoList($homePromoListExperiencias, ['date' => 'DESC']);
  158.         } else {
  159.             $homePromoExperienciasTitle null;
  160.             $homePromoExperienciasSubtitle null;
  161.             $homePromosExperiencias = [];
  162.         }
  163.         $homePromoListRecommendations $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromoList::class)->findOneBy(['type' => $promoTypeRecommendations'agency' => $agencyPromoId]);
  164.         if (null != $homePromoListRecommendations) {
  165.             $homePromoRecommendationsTitle $homePromoListRecommendations->getTitle();
  166.             $homePromoRecommendationsSubtitle $homePromoListRecommendations->getSubtitle();
  167.             $homePromosRecommendations $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromo::class)->findByHomePromoList($homePromoListRecommendations, ['date' => 'DESC']);
  168.         } else {
  169.             $homePromoRecommendationsTitle null;
  170.             $homePromoRecommendationsSubtitle null;
  171.             $homePromosRecommendations = [];
  172.         }
  173.         $configsFlightCalendarAgency $em->getRepository(\Aviatur\FlightBundle\Entity\ConfigFlightCalendarAgency::class)->findProviderForFlightsWithAgency($agency);
  174.         $providerInfo true;
  175.         $providers = [];
  176.         foreach ($configsFlightCalendarAgency as $configFlightCalendarAgency) {
  177.             $provider $configFlightCalendarAgency->getProvider()->getProvideridentifier();
  178.             if (!in_array($provider$providers)) {
  179.                 $providers[] = $provider;
  180.             }
  181.         }
  182.         $providerIds implode(';'$providers);
  183.         if (empty($providerIds)) {
  184.             $providerInfo false;
  185.         }
  186.         $newsletter = new Newsletter();
  187.         $newsletterForm $this->createForm(\Aviatur\FormBundle\Form\NewsletterAsyncType::class, $newsletter);
  188.         $isFront $session->has('operatorId');
  189.         $pixelInfo = [];
  190.         //        if (!$isFront) {
  191.         //            $pixel['dataxpand'] = true;
  192.         //            $pixelInfo = $aviaturPixeles->verifyPixeles($pixel, "home", "isActive", $agency->getAssetsFolder(), false);
  193.         //        }
  194.         $parameters json_decode($session->get($request->getHost().'[parameters]'));
  195.         if (isset($parameters->switch_redirect) && $parameters->switch_redirect == && == $agencyId) {
  196.             header('Location: https://vuelos.aviatur.com/');
  197.             exit;
  198.         }
  199.         $currentDate date('Y-m-d');
  200.         $endDateCensocud $parameters->date_end_cencosud;
  201.         $activeCheckCencosud = (strtotime($endDateCensocud) >= strtotime($currentDate));
  202.         $bannerHome $parameters->aviatur_banner_home ?? false;
  203.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  204.         if ($agency->getDomainsecure() == $agency->getDomain() && '443' != $agency->getCustomport()) {
  205.             $safeUrl 'https://'.$agency->getDomain();
  206.         } else {
  207.             $safeUrl 'https://'.$agency->getDomainsecure();
  208.         }
  209.         $agencyFolder $twigFolder->twigFlux();
  210.         $socialmedia json_decode($agency->getSocialmedia(), true);
  211.         if ($socialmedia) {
  212.             $facebook $socialmedia['Facebook'] ?? null;
  213.             $instagram $socialmedia['Instagram'] ?? null;
  214.             $linkedin $socialmedia['Linkedin'] ?? null;
  215.         }
  216.         $parameter $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneBy(['name' => 'aviatur_search_explore''value' => 1]);
  217.         $validateExplore null === $parameter 1;
  218.         $props = [
  219.             'validateExplore' => $validateExplore,
  220.             'promoSearchAgency' => $promoSearchAgency,
  221.             'blackFriday' => $activeBlackFriday,
  222.             'background_home' => $active_background_home,
  223.             'banner_home' => $bannerHome,
  224.             'pixel_info' => $pixelInfo,
  225.             'providerInfo' => $providerInfo,
  226.             'browser' => $info,
  227.             'agencyId' => $agencyId,
  228.             'cookieLastSearch' => $cookieLastSearch,
  229.             'homePromos' => $homePromos,
  230.             'titlePromo' => $homePromoTitle,
  231.             'subtitlePromo' => $homePromoSubtitle,
  232.             'promoType' => $promoType,
  233.             'homePromosRecommendations' => $homePromosRecommendations,
  234.             'titlePromoRecommendations' => $homePromoRecommendationsTitle,
  235.             'subtitlePromoRecommendations' => $homePromoRecommendationsSubtitle,
  236.             'promoTypeRecommendations' => $promoTypeRecommendations,
  237.             'homePromosBanner' => $homePromosBanners,
  238.             'titlePromoBanner' => $homePromoBannersTitle,
  239.             'subtitlePromoBanner' => $homePromoBannersSubtitle,
  240.             'promoTypeBanner' => $promoTypeBanners,
  241.             'homePromosEscapadas' => $homePromosEscapadas,
  242.             'titlePromoEscapadas' => $homePromoEscapadasTitle,
  243.             'subtitlePromoEscapadas' => $homePromoEscapadasSubtitle,
  244.             'promoTypeEscapadas' => $promoTypeEscapadas,
  245.             'homePromosExperiencias' => $homePromosExperiencias,
  246.             'titlePromoExperiencias' => $homePromoExperienciasTitle,
  247.             'subtitlePromoExperiencias' => $homePromoExperienciasSubtitle,
  248.             'promoTypeExperiencias' => $promoTypeExperiencias,
  249.             'newsletter_form' => $newsletterForm->createView(),
  250.             'activeCheckCencosud' => $activeCheckCencosud,
  251.             'safeUrl' => $safeUrl,
  252.             'validationAgencyFolder' => $validationAgencyFolder,
  253.             'linkSwitchPromos' => $linkSwitchPromos,
  254.             'socialmedia' => $socialmedia,
  255.         ];
  256.             $response $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Search/General/mainSearch_index.html.twig'), $props);
  257.         $response->setSharedMaxAge(720);
  258.         $response->headers->addCacheControlDirective('must-revalidate'true);
  259.         return $response;
  260.     }
  261.     public function loginDataAction(Request $requestManagerRegistry $registrySessionInterface $session)
  262.     {
  263.         header('Access-Control-Allow-Origin: *');
  264.         $em $registry->getManager();
  265.         $refererWhitemark $request->request->get('referer');
  266.         $whitemarkAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\Whitemark::class)->findOneBy(['referer' => $refererWhitemark]);
  267.         $data = [
  268.             'status' => 'error',
  269.         ];
  270.         if (null != $whitemarkAgency) {
  271.             $whitemarkAgencyDataInfo = [
  272.                 'whitemark_id' => $whitemarkAgency->getId(),
  273.                 'whitemark_name' => $whitemarkAgency->getName(),
  274.                 'whitemark_phone' => $whitemarkAgency->getPhone(),
  275.                 'whitemark_email' => $whitemarkAgency->getEmail(),
  276.                 'whitemark_address' => $whitemarkAgency->getAddress(),
  277.                 'whitemark_phones' => json_decode($whitemarkAgency->getPhonesContact(), true),
  278.             ];
  279.             if (count($whitemarkAgencyDataInfo) > 0) {
  280.                 $session->set('whitemarkDataInfo'$whitemarkAgencyDataInfo);
  281.                 $session->set('whitemark'$refererWhitemark);
  282.                 $data = [
  283.                     'status' => 'success',
  284.                     'data' => $whitemarkAgencyDataInfo,
  285.                 ];
  286.                 return $this->json($data);
  287.             }
  288.         } else {
  289.             return $this->json($data);
  290.         }
  291.     }
  292.     public function blankCloseAction(SessionInterface $sessionManagerRegistry $registryTwigFolder $twigFolder)
  293.     {
  294.         $em $registry->getManager();
  295.         $agencyId $session->get('agencyId');
  296.         $agencyFolder $twigFolder->twigFlux();
  297.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/General/Templates/_blankClose.html.twig'));
  298.     }
  299.     public function getOS(Request $request)
  300.     {
  301.         $user_agent $request->server->get('HTTP_USER_AGENT');
  302.         $os_platform 'unknown';
  303.         $actual_url $request->server->get('HTTP_HOST');
  304.         $os_array = [
  305.             '/windows/i' => 'windows',
  306.             '/Windows Phone/i' => 'windows',
  307.             '/MSIE/i' => 'windows',
  308.             '/macintosh|mac os x/i' => 'iphone',
  309.             '/mac_powerpc/i' => 'iphone',
  310.             '/iphone/i' => 'iphone',
  311.             '/ipod/i' => 'iphone',
  312.             '/ipad/i' => 'iphone',
  313.             '/android/i' => 'android',
  314.             '/webos/i' => 'mobile',
  315.         ];
  316.         if (false === strripos($actual_url'mobile.')) {
  317.             foreach ($os_array as $regex => $value) {
  318.                 if (preg_match($regex$user_agent)) {
  319.                     $os_platform $value;
  320.                 }
  321.             }
  322.         }
  323.         return $os_platform;
  324.     }
  325.     public function archiveAction(ParameterBagInterface $parameterBagAviaturErrorHandler $aviaturErrorHandler$id)
  326.     {
  327.         $projectDir $parameterBag->get('kernel.project_dir');
  328.         if (!file_exists($projectDir.'/app/serviceLogs/CashTransaction/'.$id)) {
  329.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '''Hubo algún problema al descargar el archivo, por favor comuníquese con nosotros a los teléfonos 57-1-5879640 o 57-1-3821616, o vía e-mail al correo soportepagoelectronico@aviatur.com.co, o revise su correo electrónico.'));
  330.         }
  331.         return new BinaryFileResponse($projectDir.'/app/serviceLogs/CashTransaction/'.$id);
  332.     }
  333.     public function changeCoinAction(Request $requestAviaturLogSave $aviaturLogSaveSessionInterface $session)
  334.     {
  335.         header('Access-Control-Allow-Origin: *');
  336.         if (false !== strpos($request->query->get('typeCountry'), '||')) {
  337.             $selectionArray explode('||'$request->query->get('typeCountry'));
  338.             $transactionId base64_decode($selectionArray[1]);
  339.             $session->set($transactionId.'[typeCoin]'$session->get('typeCoin'));
  340.             $session->set($transactionId.'[RateChange]'$session->get('RateChange'));
  341.             $session->set($transactionId.'[financialValue]'$session->get('financialValue'));
  342.             $session->set($transactionId.'[trmValue]'$session->get('trmValue'));
  343.             $aviaturLogSave->logSave(print_r([
  344.                 'typeCoin' => $session->get('typeCoin'),
  345.                 'RateChange' => $session->get('RateChange'),
  346.                 'financialValue' => $session->get('financialValue'),
  347.                 'trmValue' => $session->get('trmValue'),
  348.             ], true), 'ChangeCoinDetail''RQ'$transactionId);
  349.         }
  350.         return new Response(
  351.             json_encode(
  352.                 [
  353.                     'typeCoin' => $session->get('typeCoin'),
  354.                     'typeCountry' => $session->get('typeCountry'),
  355.                     'CoinValue' => $session->get('CoinValue'),
  356.                     'RateDiff' => $session->get('RateDiff'),
  357.                 ]
  358.             )
  359.         );
  360.     }
  361.     public function promoSearchAgencyAction(AviaturUpdatePromoProduct $aviaturUpdatePromoProduct)
  362.     {
  363.         header('Access-Control-Allow-Origin: *');
  364.         $promosAgencySearch $aviaturUpdatePromoProduct->promoSearchAgency();
  365.         return new Response($promosAgencySearch);
  366.     }
  367.     public function alertAction(Request $requestManagerRegistry $registrySessionInterface $session)
  368.     {
  369.         $alert = new Alerts();
  370.         $form $this->createForm(\Aviatur\GeneralBundle\Form\AlertsType::class, $alert);
  371.         $em $registry->getManager();
  372.         $agencyId $session->get('agencyId');
  373.         if ('POST' == $request->getMethod()) {
  374.             $form->handleRequest($request);
  375.             if ($form->isValid()) {
  376.                 if ($request->isXmlHttpRequest()) {
  377.                     $findAlert $em->getRepository(\Aviatur\GeneralBundle\Entity\Alerts::class)->findBy(['email' => $alert->getEmail(), 'url' => $alert->getUrl(), 'agency' => $agencyId]);
  378.                     if (empty($findAlert)) {
  379.                         $alert->setEntrydate(new \DateTime());
  380.                         $alert->setSearchUrl(new \DateTime());
  381.                         $bestPrice $em->getRepository(\Aviatur\GeneralBundle\Entity\BestPrices::class)->findByBestPriceUrl($alert->getUrl());
  382.                         if (!empty($bestPrice)) {
  383.                             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($agencyId);
  384.                             if (!empty($agency)) {
  385.                                 $alert->setPrice($bestPrice[0]->getBestPrice());
  386.                                 $alert->setUpdatePrice(0);
  387.                                 $alert->setTrip($bestPrice[0]->getTrip());
  388.                                 $alert->setDeparture($bestPrice[0]->getDeparture());
  389.                                 $alert->setRound($bestPrice[0]->getRound());
  390.                                 $alert->setAgency($agency);
  391.                                 $em->persist($alert);
  392.                                 $em->flush();
  393.                                 $response = new Response();
  394.                                 $output = ['success' => true];
  395.                                 $response->headers->set('Content-Type''application/json');
  396.                                 $response->setContent(json_encode($output));
  397.                                 return $response;
  398.                             } else {
  399.                                 $response = new Response();
  400.                                 $output = ['failToken' => true];
  401.                                 $response->headers->set('Content-Type''application/json');
  402.                                 $response->setContent(json_encode($output));
  403.                                 return $response;
  404.                             }
  405.                         } else {
  406.                             $response = new Response();
  407.                             $output = ['failToken' => true];
  408.                             $response->headers->set('Content-Type''application/json');
  409.                             $response->setContent(json_encode($output));
  410.                             return $response;
  411.                         }
  412.                     } else {
  413.                         $response = new Response();
  414.                         $output = ['error' => true];
  415.                         $response->headers->set('Content-Type''application/json');
  416.                         $response->setContent(json_encode($output));
  417.                         return $response;
  418.                     }
  419.                 } else {
  420.                     $response = new Response();
  421.                     $output = ['failToken' => true];
  422.                     $response->headers->set('Content-Type''application/json');
  423.                     $response->setContent(json_encode($output));
  424.                     return $response;
  425.                 }
  426.             } else {
  427.                 $response = new Response();
  428.                 $output = ['failToken' => true];
  429.                 $response->headers->set('Content-Type''application/json');
  430.                 $response->setContent(json_encode($output));
  431.                 return $response;
  432.             }
  433.         } else {
  434.             $response = new Response();
  435.             $output = ['failToken' => true];
  436.             $response->headers->set('Content-Type''application/json');
  437.             $response->setContent(json_encode($output));
  438.             return $response;
  439.         }
  440.     }
  441.     public function searchBestPricesAction(Request $requestManagerRegistry $registry)
  442.     {
  443.         $em $registry->getManager();
  444.         if ($request->isXmlHttpRequest()) {
  445.             $url $request->request->get('url');
  446.             $price $request->request->get('price');
  447.             $bestPrice $em->getRepository(\Aviatur\GeneralBundle\Entity\BestPrices::class)->findByBestPriceUrl($url);
  448.             if (!empty($bestPrice)) {
  449.                 $priceBP $bestPrice[0]->getBestprice();
  450.                 if ($price == $priceBP || $price $priceBP) {
  451.                     $response = new Response();
  452.                     $output = ['response' => 'fail'];
  453.                     $response->setContent(json_encode($output));
  454.                     return $response;
  455.                 } else {
  456.                     $response = new Response();
  457.                     $output = ['response' => 'success'];
  458.                     $response->setContent(json_encode($output));
  459.                     return $response;
  460.                 }
  461.             } else {
  462.                 $ch curl_init('http://www.aviatursym.com'.$url);
  463.                 curl_setopt($chCURLOPT_HEADERtrue);
  464.                 curl_setopt($chCURLOPT_HTTPHEADER, ['X-Requested-With: XMLHttpRequest']);
  465.                 curl_setopt($chCURLOPT_CUSTOMREQUEST'GET');
  466.                 curl_setopt($chCURLOPT_FOLLOWLOCATIONtrue);
  467.                 curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  468.                 $result curl_exec($ch);
  469.                 curl_close($ch);
  470.                 $posError strpos($result'66002');
  471.                 $posDisponibilidad strpos($result'No encontramos');
  472.                 $posFechas strpos($result'búsqueda incorrectas');
  473.                 if (false != $posError || false != $posDisponibilidad || false != $posFechas) {
  474.                     $response = new Response();
  475.                     $output = ['response' => 'fail'];
  476.                     $response->setContent(json_encode($output));
  477.                     return $response;
  478.                 } else {
  479.                     $bestPriceCURL $em->getRepository(\Aviatur\GeneralBundle\Entity\BestPrices::class)->findByBestPriceUrl($url);
  480.                     if (!empty($bestPriceCURL)) {
  481.                         $priceBP $bestPriceCURL[0]->getBestprice();
  482.                         if ($price == $priceBP || $price $priceBP) {
  483.                             $response = new Response();
  484.                             $output = ['response' => 'fail'];
  485.                             $response->setContent(json_encode($output));
  486.                             return $response;
  487.                         } else {
  488.                             $response = new Response();
  489.                             $output = ['response' => 'success'];
  490.                             $response->setContent(json_encode($output));
  491.                             return $response;
  492.                         }
  493.                     } else {
  494.                         $response = new Response();
  495.                         $output = ['response' => 'fail'];
  496.                         $response->setContent(json_encode($output));
  497.                         return $response;
  498.                     }
  499.                 }
  500.             }
  501.         } else {
  502.             $response = new Response();
  503.             $output = ['response' => 'fail'];
  504.             $response->setContent(json_encode($output));
  505.             return $response;
  506.         }
  507.     }
  508.     public function detenerAlertaAction(AviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registry$id)
  509.     {
  510.         $em $registry->getManager();
  511.         $alert $em->getRepository(\Aviatur\GeneralBundle\Entity\Alerts::class)->find($id);
  512.         if (!empty($alert)) {
  513.             $em->remove($alert);
  514.             $em->flush();
  515.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('homepage'), 'Detener alerta''La alerta ha sido eliminada de manera exitosa. Gracias por preferirnos.'));
  516.         } else {
  517.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('homepage'), 'Detener alerta''La alerta ha sido eliminada de manera exitosa. Gracias por preferirnos.'));
  518.         }
  519.     }
  520.     public function searchBestPriceXtremeAction(Request $requestManagerRegistry $registry)
  521.     {
  522.         $baseFare null;
  523.         $compareValue null;
  524.         $bestPrice null;
  525.         $airlineName null;
  526.         $em $registry->getManager();
  527.         if ($request->isXmlHttpRequest()) {
  528.             $trip $request->request->get('trip');
  529.             $dateI $request->request->get('dateInicial');
  530.             $dateF $request->request->get('dateFinal');
  531.             $flightDestination $request->request->get('destination');
  532.             $flightType $request->request->get('flightType');
  533.             $bestPrices $em->getRepository(\Aviatur\GeneralBundle\Entity\BestPrices::class)->findByBestPriceXtremeRange($trip$dateI$dateF);
  534.             if (!empty($bestPrices)) {
  535.                 $arrayLength is_countable($bestPrices) ? count($bestPrices) : 0;
  536.                 $bestP = [];
  537.                 if ('D' == $flightType) {
  538.                     for ($i 0$i $arrayLength; ++$i) {
  539.                         $prices json_decode($bestPrices[$i]->getPrices(), true);
  540.                         foreach ($prices as $price) {
  541.                             $baseFare $price['baseFare'];
  542.                             $compareValue $price['compareValue'];
  543.                             $bestPrice $price['flightPrice'];
  544.                             $airlineName $price['airlineName'];
  545.                             break;
  546.                         }
  547.                         $dateBP strtotime($bestPrices[$i]->getDeparture());
  548.                         $dateBPFormat date('dmy'$dateBP);
  549.                         $bestP[$dateBPFormat] = $bestPrice;
  550.                         $BPta $this->searchAdminFeeAction($baseFare$compareValue$bestPrice$trip$flightDestination$airlineName);
  551.                         $bestP[$dateBPFormat] = $BPta;
  552.                     }
  553.                 } elseif ('R' == $flightType) {
  554.                     for ($i 0$i $arrayLength; ++$i) {
  555.                         if ('' != $bestPrices[$i]->getRound()) {
  556.                             $prices json_decode($bestPrices[$i]->getPrices(), true);
  557.                             foreach ($prices as $price) {
  558.                                 $baseFare $price['baseFare'];
  559.                                 $compareValue $price['compareValue'];
  560.                                 $bestPrice $price['flightPrice'];
  561.                                 $airlineName $price['airlineName'];
  562.                                 break;
  563.                             }
  564.                             $dateBP strtotime($bestPrices[$i]->getRound());
  565.                             $dateBPFormat date('dmy'$dateBP);
  566.                             $bestP[$dateBPFormat] = $bestPrice;
  567.                             $BPta $this->searchAdminFeeAction($baseFare$compareValue$bestPrice$trip$flightDestination$airlineName);
  568.                             $bestP[$dateBPFormat] = $BPta;
  569.                         }
  570.                     }
  571.                 }
  572.                 $response = new Response();
  573.                 $output = ['response' => 'success''bestPrices' => $bestP];
  574.                 $response->setContent(json_encode($output));
  575.                 return $response;
  576.             } else {
  577.                 $response = new Response();
  578.                 $output = ['response' => 'fail empty'];
  579.                 $response->setContent(json_encode($output));
  580.                 return $response;
  581.             }
  582.         } else {
  583.             $response = new Response();
  584.             $output = ['response' => 'fail'];
  585.             $response->setContent(json_encode($output));
  586.             return $response;
  587.         }
  588.     }
  589.     public function searchAdminFeeAction(ManagerRegistry $registrySessionInterface $session$baseFare$compare$price$trip$destination$airline)
  590.     {
  591.         $iatas = [];
  592.         $fee = [];
  593.         $adminFe = [];
  594.         $em $registry->getManager();
  595.         $agencyR $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  596.         $destinationCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($destination);
  597.         $airlineCode $em->getRepository(\Aviatur\FlightBundle\Entity\Airline::class)->findOneByName($airline);
  598.         $adminFees $em->getRepository(\Aviatur\FlightBundle\Entity\AdminFee::class)->getAdminFeebyAgency($agencyR$destinationCity);
  599.         $fromCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('USD');
  600.         $toCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('COP');
  601.         $TRM $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->findOneBy(['fromCurrency' => $fromCurrency'toCurrency' => $toCurrency], ['id' => 'DESC']);
  602.         $claves preg_split('/[-|]+/'$trip);
  603.         $typeFlight $claves[2];
  604.         if ('R' == $typeFlight) {
  605.             $iatas[0] = $claves[0];
  606.             $iatas[1] = $claves[1];
  607.             $iatas[2] = $claves[1];
  608.             $iatas[3] = $claves[0];
  609.         } elseif ('O' == $typeFlight) {
  610.             $iatas[0] = $claves[0];
  611.             $iatas[1] = $claves[1];
  612.         }
  613.         $cityCountries $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findCountryCodes($iatas);
  614.         $airportCountries $em->getRepository(\Aviatur\SearchBundle\Entity\SearchAirports::class)->findCountryCodes($iatas);
  615.         $countries array_unique(array_merge($cityCountries$airportCountries), SORT_REGULAR);
  616.         $type '';
  617.         //VALIDACION SI ES INTERNACIONAL
  618.         if (sizeof($countries) > || (sizeof($countries) > && !in_array('CO'$countries))) {
  619.             $international true;
  620.             $isINNS 1;
  621.             $fromCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('USD');
  622.             $toCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('COP');
  623.             $TRM $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->findOneBy(['fromCurrency' => $fromCurrency'toCurrency' => $toCurrency], ['id' => 'DESC']);
  624.         } else {
  625.             $international false;
  626.             $isINNS 0;
  627.         }
  628.         if (!in_array('CO'$countries)) {
  629.             $type 'NNS';
  630.             ++$isINNS;
  631.         }
  632.         foreach ($adminFees as $key => $adminFee) {
  633.             $airline $adminFee['airline_id'];
  634.             $agency $adminFee['agency_id'];
  635.             $nnsFare = (== $adminFee['noNationalStop']) ? 'NNS' '';
  636.             $itFare = (== $adminFee['isItFare']) ? 'IT' '';
  637.             if (null != $airline) {
  638.                 $agencyFee = (null != $agency) ? 'Agency' '';
  639.                 ${'airlines'.$agencyFee.'Iata'.$nnsFare.$itFare}[] = $adminFee['iata'];
  640.                 ${'airlines'.$agencyFee.'Key'.$nnsFare.$itFare}[] = $key;
  641.             } elseif (null != $agency) {
  642.                 ${'agencyKey'.$nnsFare.$itFare} = $key;
  643.             } else {
  644.                 ${'generalKey'.$nnsFare.$itFare} = $key;
  645.             }
  646.         }
  647.         $itFare '';
  648.         $vendorCodes = !empty($airlineCode) ? [$airlineCode->getIata()] : [];
  649.         if ((isset(${'airlinesAgencyIata'.$type.$itFare}) && ((bool) array_intersect(${'airlinesAgencyIata'.$type.$itFare}, $vendorCodes))) || (isset(${'airlinesIata'.$type.$itFare}) && ((bool) array_intersect(${'airlinesIata'.$type.$itFare}, $vendorCodes)))) {
  650.             $agencyFee = (isset(${'airlinesAgencyIata'.$type.$itFare}) && ((bool) array_intersect(${'airlinesAgencyIata'.$type.$itFare}, $vendorCodes))) ? 'Agency' '';
  651.             $purgeAirlinesIata array_unique(array_intersect(${'airlines'.$agencyFee.'Iata'.$type.$itFare}, $vendorCodes));
  652.             foreach ($purgeAirlinesIata as $airlineIata) {
  653.                 $airlineIatasToFee array_keys(${'airlines'.$agencyFee.'Iata'.$type.$itFare}, $airlineIata);
  654.                 $fee null;
  655.                 foreach ($airlineIatasToFee as $indexFee) {
  656.                     $optionalFee $adminFees[${'airlines'.$agencyFee.'Key'.$type.$itFare}[$indexFee]];
  657.                     if (null != $optionalFee['city_id'] && $optionalFee['city_id'] == (string) $destinationCity->getId()) {
  658.                         $fee $optionalFee;
  659.                     }
  660.                 }
  661.                 if (null == $fee) {
  662.                     $fee $adminFees[${'airlines'.$agencyFee.'Key'.$type.$itFare}[array_search($airlineIata, ${'airlines'.$agencyFee.'Iata'.$type.$itFare})]];
  663.                 }
  664.             }
  665.         } elseif (isset(${'agencyKey'.$type.$itFare})) {
  666.             $fee $adminFees[${'agencyKey'.$type.$itFare}];
  667.         } elseif (isset(${'generalKey'.$type.$itFare})) {
  668.             $fee $adminFees[${'generalKey'.$type.$itFare}];
  669.         } else {
  670.             $fee null;
  671.             //                            echo "ERROR: tarifa " . $type . " no encontrada para la aerolinea: " . $airlineIata . " y la agencia con id: " . $agency;
  672.             $administrativeCost 0;
  673.         }
  674.         $administrativeCost 0;
  675.         if (== $fee['rangeType']) {
  676.             if ($international) {
  677.                 $compareValue $compare $TRM->getRate()->getFinantialrate();
  678.                 if (($fee['rangeInternational1Start'] <= $compareValue) && ($compareValue <= $fee['rangeInternational1End'])) {
  679.                     $administrativeCostRange $fee['valueInternational1'];
  680.                 } elseif (($fee['rangeInternational2Start'] <= $compareValue) && ($compareValue <= $fee['rangeInternational2End'])) {
  681.                     $administrativeCostRange $fee['valueInternational2'];
  682.                 } elseif (($fee['rangeInternational3Start'] <= $compareValue) && ($compareValue <= $fee['rangeInternational3End'])) {
  683.                     $administrativeCostRange $fee['valueInternational3'];
  684.                 } elseif (($fee['rangeInternational4Start'] <= $compareValue) && ($compareValue <= $fee['rangeInternational4End'])) {
  685.                     $administrativeCostRange $fee['valueInternational4'];
  686.                 } elseif (($fee['rangeInternational4Start'] <= $compareValue) && == $fee['rangeInternational4End']) {
  687.                     $administrativeCostRange $adminFe['valueInternational4'];
  688.                 } else {
  689.                     $administrativeCostRange 0;
  690.                 }
  691.                 if (== $fee['valueType']) {
  692.                     $administrativeCost += round($administrativeCostRange $TRM->getRate()->getFinantialrate() * 1);
  693.                 } else {
  694.                     $administrativeCost += round(($baseFare /* + ${'tax' . $infoPassenger['Code']} */) * $administrativeCostRange);
  695.                 }
  696.             } else {
  697.                 if (== $fee['valueType']) {
  698.                     if ('R' == $typeFlight) {
  699.                         $administrativeCost $fee['roundtripNational'];
  700.                     } else {
  701.                         $administrativeCost $fee['onewayNational'];
  702.                     }
  703.                     $administrativeCost $administrativeCost 1;
  704.                 } else {
  705.                     if ('R' == $typeFlight) {
  706.                         $administrativeCost $fee['roundtripNational'];
  707.                     } else {
  708.                         $administrativeCost $fee['onewayNational'];
  709.                     }
  710.                     $administrativeCost $baseFare $administrativeCost;
  711.                 }
  712.             }
  713.         } else {
  714.             if ($international) {
  715.                 $administrativeCost $fee['internationalFixed'];
  716.                 if (== $fee['valueType']) {
  717.                     $administrativeCost round($administrativeCost $TRM->getRate()->getFinantialrate());
  718.                 }
  719.             } else {
  720.                 $administrativeCost $fee['nationalFixed'];
  721.             }
  722.             if ($fee['valueType']) {
  723.                 $administrativeCost $price $administrativeCost;
  724.             } else {
  725.                 $administrativeCost $administrativeCost 1;
  726.             }
  727.         }
  728.         $fare = (int) $price + (int) $administrativeCost.'.00';
  729.         return (string) $fare;
  730.     }
  731.     public function filesRssAction(ManagerRegistry $registrySessionInterface $sessionTwigFolder $twigFolder)
  732.     {
  733.         $em $registry->getManager();
  734.         $agencyId $session->get('agencyId');
  735.         $agencyFolder $twigFolder->twigFlux();
  736.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/General/Templates/filesRss.html.twig'));
  737.     }
  738.     public function daviviendaLoginAction(Request $requestManagerRegistry $registrySessionInterface $sessionParameterBagInterface $parameterBagTwigFolder $twigFolder)
  739.     {
  740.         $env $parameterBag->get('kernel.environment');
  741.         $response = [];
  742.         $environment $env;
  743.         $em $registry->getManager();
  744.         $parameters json_decode($em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_davivienda')->getDescription(), true);
  745.         $urlAuthentication $parameters['endPoints']['authentication'][$environment].'?client_id='.$parameters['idCliente'].'&response_type='.$parameters['responsetype'].'&scope='.$parameters['scope'];
  746.         $agencyFolder $twigFolder->twigFlux();
  747.         $urlReturn '@AviaturTwig/'.$agencyFolder.'/Payment/Davivienda/loginReturn.html.twig';
  748.         if ($request->isXmlHttpRequest()) {
  749.             if (!empty(json_decode($request->getContent(), true))) {
  750.                 $parametersAsArray = [];
  751.                 if ($content $request->getContent()) {
  752.                     $parametersAsArray json_decode($contenttrue);
  753.                 }
  754.                 if (empty($parametersAsArray)) {
  755.                     $response $this->returnResult('error'500'1. Error con los parametros de entrada.');
  756.                 }
  757.                 if (isset($parametersAsArray['authentication'])) {
  758.                     $url $parameters['endPointsApi']['authentication'][$environment];
  759.                     $response $this->CallAPI($urlfalsefalse'authentication');
  760.                     if (isset($response['message']) && isset($response['message']['text']['token'])) {
  761.                         $response['message']['text']['session'] = true;
  762.                         $session->set('[davivienda][token]'$response['message']['text']['token']);
  763.                     }
  764.                 } elseif (isset($parametersAsArray['token'])) {
  765.                     $url $parameters['endPointsApi']['logindavivienda'][$environment];
  766.                     $response $this->CallAPI($url, ['token' => $parametersAsArray['token']], false'login-davivienda');
  767.                 }
  768.             } else {
  769.                 $response $this->returnResult('error'500'1. Error con los parametros de entrada.');
  770.             }
  771.         } elseif (!empty($request->query->get('rstate'))) {
  772.             $infos = ['rstate''confirmation''username'];
  773.             foreach ($infos as $info) {
  774.                 if (!$request->query->has($info) || empty($request->query->has($info))) {
  775.                     $response $this->returnResult('error'500'Error en parametro = '.$info);
  776.                 }
  777.             }
  778.             $redirect_uri $parameters['redirect_uri'];
  779.             $rstate $request->query->get('rstate');
  780.             $confirmation $request->query->get('confirmation');
  781.             $username $request->query->get('username');
  782.             $url $urlAuthentication.'&redirect_uri='.$redirect_uri.'&rstate='.$rstate.'&confirmation='.$confirmation.'&username='.$username;
  783.             $response $this->CallAPI($urlfalsefalse'authentication_redirect');
  784.             if (isset($response['message']) && isset($response['message']['text']['access_token'])) {
  785.                 if ($session->has('[davivienda][token]')) {
  786.                     $token $session->get('[davivienda][token]');
  787.                     $accesToken $em->getRepository(\Aviatur\RestBundle\Entity\OauthAccesstokenDavivienda::class)->findOneByToken($token);
  788.                     $response['message']['text']['token'] = $token;
  789.                     $externalLogin = [
  790.                         'login' => true,
  791.                         'access_token' => $response['message']['text']['access_token'],
  792.                         'token_type' => $response['message']['text']['token_type'],
  793.                         'token' => $token,
  794.                     ];
  795.                     $accesToken->setExternalLogin(json_encode($externalLogin));
  796.                     $em->persist($accesToken);
  797.                     $em->flush();
  798.                 } else {
  799.                     $response $this->returnResult('error'500'2. No existe token.');
  800.                 }
  801.             } else {
  802.                 $response $this->returnResult('error'500'1. No existe Token.');
  803.             }
  804.             return $this->render($twigFolder->twigExists($urlReturn), ['response' => $response]);
  805.         } else {
  806.             $response $this->returnResult('error'500'No existe Informacion.');
  807.             return $this->render($twigFolder->twigExists($urlReturn), ['response' => $response]);
  808.         }
  809.         return $this->json($response);
  810.     }
  811.     public function validCaptchaAction(Request $request)
  812.     {
  813.         if ($request->isXmlHttpRequest()) {
  814.             $token $request->request->get('g-recaptcha-response');
  815.             $secretKey '6LfsqrgZAAAAAEuDXSOrdZloUv_T5qC6uu7qdXQE';
  816.             $request 'https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$token;
  817.             $arrContextOptions = [
  818.                 'ssl' => [
  819.                     'verify_peer' => false,
  820.                     'verify_peer_name' => false,
  821.                 ],
  822.             ];
  823.             $verifydata file_get_contents($requestfalsestream_context_create($arrContextOptions));
  824.             $response json_decode($verifydata);
  825.             if ($response->success) {
  826.                 return $this->json(['status' => 'success''message' => 'Captcha valido']);
  827.             } else {
  828.                 return $this->json(['status' => 'error''message' => 'Captcha inválido']);
  829.             }
  830.         }
  831.     }
  832.     // Poner siempre la palabra Action al final de la funcion
  833.     public function UserApiAction(Request $requestManagerRegistry $registry)
  834.     {
  835.         $em $registry->getManager();
  836.         $registros $request->request->get('registros');
  837.         $pagina $request->request->get('pagina');
  838.         $pagina = ($pagina 10) - 10;
  839.         $totalRegistros $em->createQuery('SELECT count(:total) FROM AviaturCustomerBundle:Customer')->setParameter('total''*');
  840.         $total $totalRegistros->getResult();
  841.         $numPaginas = (int) $total[0]['1'] / $registros;
  842.         $allUsers $em->createQuery('SELECT c.firstname, c.id FROM AviaturCustomerBundle:Customer c ORDER BY c.id DESC')->setMaxResults($registros)->setFirstResult($pagina);
  843.         $users $allUsers->getResult();
  844.         return $this->json(['status' => 'success''code' => 200'totalPages' => $numPaginas'data' => $users]);
  845.     }
  846.     public function getAllAdmiFeeWmAction(ManagerRegistry $registry)
  847.     {
  848.         $em $registry->getManager();
  849.         //$token = $request->request->get('g-recaptcha-response');
  850.         $info $em->getRepository(\Aviatur\FlightBundle\Entity\AdminFeeWhitemark::class)->findAll();
  851.         if (!$info) {
  852.             return $this->json(['status' => 'error''code' => 200'message' => 'No hay registros']);
  853.         }
  854.         $data = [];
  855.         foreach ($info as $item) {
  856.             $arrayTemp = [
  857.                 'id' => $item->getId(),
  858.                 'whitemarkId' => (null == $item->getWhitemark()) ? null : (int) $item->getWhitemark()->getId(),
  859.                 'airlineId' => (null == $item->getAirline()) ? null : (int) $item->getAirline()->getId(),
  860.                 'cityId' => (null == $item->getCity()) ? null : (int) $item->getCity()->getId(),
  861.                 'valueType' => (int) $item->getValuetype(),
  862.                 'rangeType' => (int) $item->getRangetype(),
  863.                 'isActive' => (int) $item->getIsactive(),
  864.                 'noNationalStop' => (int) $item->getNonationalstop(),
  865.                 'isItFare' => (int) $item->getIsitfare(),
  866.                 'nationalFixed' => $item->getNationalfixed(),
  867.                 'internationalFixed' => $item->getInternationalfixed(),
  868.                 'roundtripNational' => $item->getRoundtripnational(),
  869.                 'onewayNational' => $item->getOnewaynational(),
  870.                 'rangeInternational1Start' => $item->getRangeinternational1start(),
  871.                 'rangeInternational1End' => $item->getRangeinternational1end(),
  872.                 'rangeInternational2Start' => $item->getRangeinternational2start(),
  873.                 'rangeInternational2End' => $item->getRangeinternational2end(),
  874.                 'rangeInternational3Start' => $item->getRangeinternational3start(),
  875.                 'rangeInternational3End' => $item->getRangeinternational3end(),
  876.                 'rangeInternational4Start' => $item->getRangeinternational4start(),
  877.                 'rangeInternational4End' => $item->getRangeinternational4end(),
  878.                 'valueInternational1' => $item->getValueinternational1(),
  879.                 'valueInternational2' => $item->getValueinternational2(),
  880.                 'valueInternational3' => $item->getValueinternational3(),
  881.                 'valueInternational4' => $item->getValueinternational4(),
  882.             ];
  883.             array_push($data$arrayTemp);
  884.         }
  885.         return $this->json(['status' => 'success''code' => 200'data' => $data]);
  886.     }
  887.     public function addNewAdmiFeeWmAction(Request $requestManagerRegistry $registry)
  888.     {
  889.         $em $registry->getManager();
  890.         if ($request->request->get('cityId') && '' != $request->request->get('cityId') && null != $request->request->get('cityId')) {
  891.             $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneBy(['id' => (int) $request->request->get('cityId')]);
  892.             if (!$dataCity) {
  893.                 return $this->json(['status' => 'error''code' => 200'message' => 'No existe registro para la ciudad indicada']);
  894.             }
  895.         }
  896.         if ($request->request->get('airlineId') && '' != $request->request->get('airlineId') && null != $request->request->get('airlineId')) {
  897.             $airline $em->getRepository(\Aviatur\FlightBundle\Entity\Airline::class)->findOneBy(['id' => (int) $request->request->get('airlineId')]);
  898.             if (!$airline) {
  899.                 return $this->json(['status' => 'error''code' => 200'message' => 'No existe registro para la aerolinea indicada']);
  900.             }
  901.         }
  902.         if ($request->request->get('whitemarkId') && '' != $request->request->get('whitemarkId') && null != $request->request->get('whitemarkId')) {
  903.             $whitemark $em->getRepository(\Aviatur\GeneralBundle\Entity\Whitemark::class)->findOneBy(['id' => (int) $request->request->get('whitemarkId')]);
  904.             if (!$whitemark) {
  905.                 return $this->json(['status' => 'error''code' => 200'message' => 'No existe registro para la Whitemark indicada']);
  906.             }
  907.         }
  908.         $data = new AdminFeeWhitemark();
  909.         $data->setWhitemark($whitemark ?? null);
  910.         $data->setAirline($airline ?? null);
  911.         $data->setCity($dataCity ?? null);
  912.         $data->setValuetype(($request->request->get('valuetype') && '' != $request->request->get('valuetype') && null != $request->request->get('valuetype')) ? (int) $request->request->get('valuetype') : null);
  913.         $data->setRangetype(($request->request->get('rangetype') && '' != $request->request->get('rangetype') && null != $request->request->get('rangetype')) ? (int) $request->request->get('rangetype') : null);
  914.         $data->setIsactive(($request->request->get('isactive') && '' != $request->request->get('isactive') && null != $request->request->get('isactive')) ? (int) $request->request->get('isactive') : null);
  915.         $data->setNonationalstop(($request->request->get('nonationalstop') && '' != $request->request->get('nonationalstop') && null != $request->request->get('nonationalstop')) ? (int) $request->request->get('nonationalstop') : null);
  916.         $data->setIsitfare(($request->request->get('isitfare') && '' != $request->request->get('isitfare') && null != $request->request->get('isitfare')) ? (int) $request->request->get('isitfare') : null);
  917.         $data->setNationalfixed(($request->request->get('nationalfixed') && '' != $request->request->get('nationalfixed') && null != $request->request->get('nationalfixed')) ? (float) $request->request->get('nationalfixed') : 0);
  918.         $data->setInternationalfixed(($request->request->get('internationalfixed') && '' != $request->request->get('internationalfixed') && null != $request->request->get('internationalfixed')) ? (float) $request->request->get('internationalfixed') : 0);
  919.         $data->setRoundtripnational(($request->request->get('roundtripnational') && '' != $request->request->get('roundtripnational') && null != $request->request->get('roundtripnational')) ? (float) $request->request->get('roundtripnational') : 0);
  920.         $data->setOnewaynational(($request->request->get('onewaynational') && '' != $request->request->get('onewaynational') && null != $request->request->get('onewaynational')) ? (float) $request->request->get('onewaynational') : 0);
  921.         $data->setRangeinternational1start(($request->request->get('rangeinternational1start') && '' != $request->request->get('rangeinternational1start') && null != $request->request->get('rangeinternational1start')) ? (int) $request->request->get('rangeinternational1start') : 0);
  922.         $data->setRangeinternational1end(($request->request->get('rangeinternational1end') && '' != $request->request->get('rangeinternational1end') && null != $request->request->get('rangeinternational1end')) ? (int) $request->request->get('rangeinternational1end') : 0);
  923.         $data->setRangeinternational2start(($request->request->get('rangeinternational2start') && '' != $request->request->get('rangeinternational2start') && null != $request->request->get('rangeinternational2start')) ? (int) $request->request->get('rangeinternational2start') : 0);
  924.         $data->setRangeinternational2end(($request->request->get('rangeinternational2end') && '' != $request->request->get('rangeinternational2end') && null != $request->request->get('rangeinternational2end')) ? (int) $request->request->get('rangeinternational2end') : 0);
  925.         $data->setRangeinternational3start(($request->request->get('rangeinternational3start') && '' != $request->request->get('rangeinternational3start') && null != $request->request->get('rangeinternational3start')) ? (int) $request->request->get('rangeinternational3start') : 0);
  926.         $data->setRangeinternational3end(($request->request->get('rangeinternational3end') && '' != $request->request->get('rangeinternational3end') && null != $request->request->get('rangeinternational3end')) ? (int) $request->request->get('rangeinternational3end') : 0);
  927.         $data->setRangeinternational4start(($request->request->get('rangeinternational4start') && '' != $request->request->get('rangeinternational4start') && null != $request->request->get('rangeinternational4start')) ? (int) $request->request->get('rangeinternational4start') : 0);
  928.         $data->setRangeinternational4end(($request->request->get('rangeinternational4end') && '' != $request->request->get('rangeinternational4end') && null != $request->request->get('rangeinternational4end')) ? (int) $request->request->get('rangeinternational4end') : 0);
  929.         $data->setValueinternational1(($request->request->get('valueinternational1') && '' != $request->request->get('valueinternational1') && null != $request->request->get('valueinternational1')) ? (float) $request->request->get('valueinternational1') : 0);
  930.         $data->setValueinternational2(($request->request->get('valueinternational2') && '' != $request->request->get('valueinternational2') && null != $request->request->get('valueinternational2')) ? (float) $request->request->get('valueinternational2') : 0);
  931.         $data->setValueinternational3(($request->request->get('valueinternational3') && '' != $request->request->get('valueinternational3') && null != $request->request->get('valueinternational3')) ? (float) $request->request->get('valueinternational3') : 0);
  932.         $data->setValueinternational4(($request->request->get('valueinternational4') && '' != $request->request->get('valueinternational4') && null != $request->request->get('valueinternational4')) ? (float) $request->request->get('valueinternational4') : 0);
  933.         $em->persist($data);
  934.         $em->flush();
  935.         return $this->json(['status' => 'success''code' => 200'message' => 'Registro creado']);
  936.     }
  937.     public function getAllCityAction(ManagerRegistry $registry)
  938.     {
  939.         $em $registry->getManager();
  940.         $cities $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findAll();
  941.         $data = [];
  942.         foreach ($cities as $item) {
  943.             $arrayTemp = [
  944.                 'id' => $item->getId(),
  945.                 'iataCode' => $item->getIataCode(),
  946.                 'description' => ucfirst(strtolower($item->getDescription())),
  947.             ];
  948.             array_push($data$arrayTemp);
  949.         }
  950.         return $this->json(['status' => 'success''code' => 200'data' => $data]);
  951.     }
  952.     public function getAllAirlinesAction(ManagerRegistry $registry)
  953.     {
  954.         $em $registry->getManager();
  955.         $airlines $em->getRepository(\Aviatur\FlightBundle\Entity\Airline::class)->findAll();
  956.         $data = [];
  957.         foreach ($airlines as $item) {
  958.             $arrayTemp = [
  959.                 'id' => $item->getId(),
  960.                 'iataCode' => $item->getIata(),
  961.                 'description' => ucfirst(strtolower($item->getName())),
  962.             ];
  963.             array_push($data$arrayTemp);
  964.         }
  965.         return $this->json(['status' => 'success''code' => 200'data' => $data]);
  966.     }
  967.     public function CallAPI($url$data false$bearer false$method false)
  968.     {
  969.         $curl curl_init();
  970.         $curlSet = [
  971.             CURLOPT_URL => $url,
  972.             CURLOPT_SSL_VERIFYPEER => false,
  973.             CURLOPT_RETURNTRANSFER => true,
  974.             CURLOPT_HEADER => true,
  975.             CURLOPT_ENCODING => '',
  976.             CURLOPT_MAXREDIRS => 10,
  977.             CURLOPT_TIMEOUT => 30,
  978.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  979.         ];
  980.         switch ($method) {
  981.             case 'authentication':
  982.                 $curlSet[CURLOPT_SSLCERT] = 'C:/davivienda/BancoDavivienda.cer';
  983.                 $curlSet[CURLOPT_SSLKEY] = 'C:/davivienda/bancodavivienda.key';
  984.                 $curlSet[CURLOPT_SSLCERTPASSWD] = 'davivienda';
  985.                 $curlSet[CURLOPT_SSL_VERIFYHOST] = false;
  986.                 $curlSet[CURLOPT_CUSTOMREQUEST] = 'POST';
  987.                 break;
  988.             case 'login-davivienda':
  989.                 $curlSet[CURLOPT_SSL_VERIFYHOST] = false;
  990.                 $curlSet[CURLOPT_CUSTOMREQUEST] = 'POST';
  991.                 $curlSet[CURLOPT_POSTFIELDS] = json_encode(['token' => $data['token']]);
  992.                 break;
  993.             case 'authentication_redirect':
  994.                 $curlSet[CURLOPT_SSLCERT] = 'C:/davivienda/BancoDavivienda.cer';
  995.                 $curlSet[CURLOPT_SSLKEY] = 'C:/davivienda/bancodavivienda.key';
  996.                 $curlSet[CURLOPT_SSLCERTPASSWD] = 'davivienda';
  997.                 $curlSet[CURLOPT_CUSTOMREQUEST] = 'GET';
  998.                 break;
  999.         }
  1000.         curl_setopt_array($curl$curlSet);
  1001.         $execute curl_exec($curl);
  1002.         $err curl_error($curl);
  1003.         $curl_info curl_getinfo($curl);
  1004.         $http_code $curl_info['http_code'];
  1005.         $header_size curl_getinfo($curlCURLINFO_HEADER_SIZE);
  1006.         $body json_decode(str_replace('/''\\\\'substr($execute$header_size)), true);
  1007.         $response $body;
  1008.         if (isset($body['httpCode'])) {
  1009.             $http_code $body['httpCode'];
  1010.         } elseif (isset($body['errorCode'])) {
  1011.             $http_code $body['errorCode'];
  1012.         }
  1013.         curl_close($curl);
  1014.         if ($err) {
  1015.             $response['error'] = 'cURL Error #: '.$err;
  1016.             $type 'error';
  1017.         } else {
  1018.             $type = (302 == $http_code || 200 == $http_code) ? 'message' 'error';
  1019.             switch ($method) {
  1020.                 case 'authentication_redirect':
  1021.                     //$urlreturn = 'https://www.aviatur.com/openapi/davivienda/login#access_token=AAIkNDg1MGRiOTQtODFmMC00ZThmLTk3NmUtM2JiZjM5NjEzMTM035hlZ6nqeCVMkZNldW_hgQO6XAsZJ2WenNmi6s73jqr4Ychp1sRck_eg8Up4_P3TqPcqkhtrW94KB3Gv0y0WWi3CoRvHbdM_66cupUUOpdTC1u_yLoORqCBt36scZtZu75tbRs1Ir51vsL36XU7ngA&expires_in=900&scope=review&token_type=bearer';
  1022.                     $urlreturn $curl_info['redirect_url'];
  1023.                     $url_parts parse_url($urlreturn);
  1024.                     if (isset(parse_url($urlreturn)['fragment']) && false !== strpos(parse_url($urlreturn)['fragment'], '=')) {
  1025.                         $fragment explode('&'parse_url($urlreturn)['fragment']);
  1026.                         foreach ($fragment as $url) {
  1027.                             $parameter explode('='$url);
  1028.                             $response[$parameter[0]] = $parameter[1];
  1029.                         }
  1030.                     }
  1031.                     break;
  1032.                 default:
  1033.                     return $response;
  1034.                     break;
  1035.             }
  1036.         }
  1037.         return $this->returnResult($type$http_code$response);
  1038.     }
  1039.     private function returnResult($type$code$text)
  1040.     {
  1041.         return [
  1042.             $type => [
  1043.                 'code' => $code,
  1044.                 'text' => $text,
  1045.             ],
  1046.         ];
  1047.     }
  1048.     public function pSliderAction(SessionInterface $sessionManagerRegistry $registryTwigFolder $twigFolder)
  1049.     {
  1050.         $em $registry->getManager();
  1051.         $agencyId $session->get('agencyId');
  1052.         $agencyFolder $twigFolder->twigFlux();
  1053.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Content/Content/pSlider.html.twig'));
  1054.     }
  1055.     public function wmNewAction(Request $requestManagerRegistry $registry)
  1056.     {
  1057.         $em $registry->getManager();
  1058.         $data json_decode($request->getContent());
  1059.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->findOneByName($data->agency);
  1060.         if (is_object($agency)) {
  1061.             $data->agency $agency;
  1062.             $whitemark = new Whitemark();
  1063.             foreach ($data as $key => $value) {
  1064.                 $setter 'set'.ucfirst($key);
  1065.                 $whitemark->$setter($value);
  1066.             }
  1067.             $em->persist($whitemark);
  1068.             $em->flush();
  1069.             return $this->json(['status' => 'success''message' => 'Marca blanca creada correctamente.']);
  1070.         } else {
  1071.             return $this->json(['status' => 'error''message' => 'La agencia relacionada no existe']);
  1072.         }
  1073.     }
  1074.     public function wmUploadImageAction(Request $requestParameterBagInterface $parameterBag)
  1075.     {
  1076.         $projectDir $parameterBag->get('kernel.project_dir');
  1077.         if ($request && $request->isMethod('POST')) {
  1078.             $baseDir $projectDir.'/web/assets/whitemark_assets/img/header';
  1079.             /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
  1080.             $file $request->files->get('image');
  1081.             if ($file) {
  1082.                 if ('image/png' == $file->getClientMimeType() || 'image/jpeg' == $file->getClientMimeType()) {
  1083.                     try {
  1084.                         $file->move(
  1085.                             $baseDir,
  1086.                             $file->getClientOriginalName()
  1087.                         );
  1088.                         return $this->json(['status' => 'success''message' => 'Imagen cargada correctamente.']);
  1089.                     } catch (FileException $e) {
  1090.                         return $this->json(['status' => 'error''message' => $e]);
  1091.                     }
  1092.                 } else {
  1093.                     return $this->json(['status' => 'error''message' => 'Archivo no permitido [03]']);
  1094.                 }
  1095.             } else {
  1096.                 return $this->json(['status' => 'error''message' => 'Ha ocurrido un error [01]']);
  1097.             }
  1098.         } else {
  1099.             return $this->json(['status' => 'error''message' => 'Datos invalidos [02]']);
  1100.         }
  1101.     }
  1102.     //
  1103.     //    public function talentosAction() {
  1104.     //        $request = $this->get('request_stack')->getCurrentRequest()->request;
  1105.     //        $postData = $request->all();
  1106.     //        $body = "Votación talentos aviatur: <br>"
  1107.     //                . "Nombre: " . $postData['Nombre'] . "<br>"
  1108.     //                . "Cedula: " . $postData['Cedula'] . "<br>"
  1109.     //                . "Oficina: " . $postData['Oficina'] . "<br>"
  1110.     //                . "Voto: " . $postData['Voto'];
  1111.     //        $message = (new \Swift_Message())
  1112.     //                ->setContentType("text/html")
  1113.     //                ->setFrom(array('noreply@aviatur.com.co' => 'Talentos Aviatur'))
  1114.     //                ->setTo(array('talentosaviatur@aviatur.com'))
  1115.     //                ->setBcc(array('gustavo.hincapie@aviatur.com'))
  1116.     //                ->setSubject('Votación Talentos')
  1117.     //                ->setBody($body);
  1118.     //        $this->container->get('mailer')->send($message);
  1119.     //        return $this->redirect('http://talentosaviatur.com/index.php/votacion-exitosa');
  1120.     //    }
  1121.     //
  1122.     //    public function votacionHappyAction() {
  1123.     //        $request = $this->get('request_stack')->getCurrentRequest()->request;
  1124.     //        $postData = $request->all();
  1125.     //        $body = "Votación Video Happy Aviatur: <br>"
  1126.     //                . "Nombre: " . $postData['Nombre'] . "<br>"
  1127.     //                . "Cedula: " . $postData['Cedula'] . "<br>"
  1128.     //                . "Oficina: " . $postData['Oficina'] . "<br>"
  1129.     //                . "Voto: " . $postData['Voto'];
  1130.     //        $message = (new \Swift_Message())
  1131.     //                ->setContentType("text/html")
  1132.     //                ->setFrom(array('noreply@aviatur.com.co' => 'Votación Video Happy Aviatur'))
  1133.     //                ->setTo(array('talentosaviatur@aviatur.com'))
  1134.     //                ->setBcc(array('gustavo.hincapie@aviatur.com'))
  1135.     //                ->setSubject('Votación Talentos')
  1136.     //                ->setBody($body);
  1137.     //        $this->container->get('mailer')->send($message);
  1138.     //        return $this->redirect('http://talentosaviatur.com/index.php/votacion-exitosa');
  1139.     //    }
  1140. }