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

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