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