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

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