Guest User

Untitled

a guest
Aug 8th, 2017
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 118.66 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Enalquiler\Modules\Elastica\Handler;
  4.  
  5. use Elastica\Request;
  6. use Elastica\ResultSet;
  7. use Enalquiler\Core\DI\DIContainer;
  8. use Enalquiler\Core\Environment\Environment;
  9. use Enalquiler\Modules\Elastica\Manager\ElasticaQueryBuilder;
  10. use Enalquiler\Modules\Product\Service\BookingOnline;
  11. use Enalquiler\Modules\Product\Service\Service;
  12. use Enalquiler\Modules\Search\Handler\SearchHandlerInterface;
  13. use Enalquiler\Modules\Search\ListHelper\DataProvider;
  14. use TextUtilities;
  15.  
  16. /**
  17. * Default search handler.
  18. *
  19. * @author Francesc Roldán <francesc@enalquiler.com>
  20. * */
  21. class ElasticaSearchHandler implements SearchHandlerInterface
  22. {
  23. const ONLY_FULL_PROPERTY = 1;
  24. const ONLY_ROOMS = 2;
  25. const NOT_SMOKE_FILTER = 2;
  26.  
  27. /**
  28. * Search params array variable.
  29. *
  30. * @var array
  31. * */
  32. protected $search_params = [];
  33. protected $aggregations = [];
  34. protected $highlight = [];
  35. protected $queryType = [];
  36. protected $parameters = [];
  37. protected $debug = '';
  38.  
  39. /**
  40. * Query builder.
  41. *
  42. * @var \Enalquiler\Modules\Elastica\Manager\ElasticaQueryBuilder
  43. * */
  44. private $qb;
  45.  
  46. /**
  47. * Logger.
  48. *
  49. * @var \Enalquiler\Core\Log\LogInterface
  50. * */
  51. private $logger;
  52.  
  53. /**
  54. * @var Environment
  55. */
  56. private $environment;
  57.  
  58. /**
  59. * Constructor.
  60. *
  61. * @param \Doctrine\Common\Persistence\ManagerRegistry $doctrine
  62. *
  63. * @author
  64. * */
  65. public function __construct(ElasticaQueryBuilder $qb, $logger)
  66. {
  67. $this->qb = $qb;
  68. $this->logger = $logger;
  69. }
  70.  
  71. /**
  72. * Execute the search action and returns the result set.
  73. *
  74. * @return array An array of search results
  75. * @throws \Exception
  76. */
  77. public function execute()
  78. {
  79. if (!$this->qb instanceof ElasticaQueryBuilder) {
  80. throw new \Exception('Query builder not found');
  81. }
  82.  
  83. if (!isset($this->search_params['searchType']) || !$this->search_params['searchType']) {
  84. throw new \Exception('Search type not set');
  85. }
  86.  
  87. $results = [];
  88. switch ($this->search_params['searchType']) {
  89. case 'search_results':
  90. $results = $this->getSearchResults();
  91. break;
  92.  
  93. case 'search_province':
  94. $results = $this->getSearchProvince();
  95. break;
  96.  
  97. case 'boosted_close_locations':
  98. $results = $this->getBoostedCloseLocations();
  99. break;
  100.  
  101. case 'search_close_locations':
  102. $results = $this->getSearchCloseLocations();
  103. break;
  104.  
  105. case 'search_provinces':
  106. $results = $this->getProvinceCounts();
  107. break;
  108.  
  109. case 'search_cities':
  110. $results = $this->getCityCountsByProvince();
  111. break;
  112.  
  113. case 'search_ajax_ficha':
  114. $results = $this->getPropertyNavigation();
  115. break;
  116.  
  117. case 'search_total':
  118. $results = $this->getSearchTotal();
  119. break;
  120.  
  121. case 'provinces_counts':
  122. $results = $this->getSuggestProvincesCounts();
  123. break;
  124.  
  125. case 'cities_counts':
  126. $results = $this->getSuggestCitiesCounts();
  127. break;
  128.  
  129. case 'districts_counts':
  130. $results = $this->getSuggestDistrictsCounts();
  131. break;
  132.  
  133. case 'neighborhoods_counts':
  134. $results = $this->getSuggestNeighborhoodsCounts();
  135. break;
  136.  
  137. case 'search_last_properties':
  138. $results = $this->getSearchLastProperties();
  139. break;
  140.  
  141. case 'search_related_properties':
  142. $results = $this->getSearchRelatedProperties();
  143. break;
  144. case 'search_min_price_property':
  145. $results = $this->getSearchMinPrice();
  146. break;
  147.  
  148. case 'suggest_home':
  149. $results = $this->getSuggestHome();
  150. break;
  151.  
  152. case 'search_favourites':
  153. $results = $this->getSearchFavourites();
  154. break;
  155.  
  156. case 'search_boosted_properties':
  157. $results = $this->getSearchBoostedProperties();
  158. break;
  159. case 'search_expert_agency':
  160. $results = $this->getSearchExpertAgencyProperties();
  161. break;
  162.  
  163. case 'categories_count':
  164. $results = $this->getSearchCategoriesCounts();
  165. break;
  166.  
  167. case 'capital_province_count':
  168. $results = $this->getSearchCapitalProvinceCounts();
  169. break;
  170.  
  171. case 'search_alert_properties':
  172. $results = $this->getSearchAlertProperties();
  173. break;
  174.  
  175. case 'search_api_iphone':
  176. $results = $this->getSearchApiIphone();
  177. break;
  178.  
  179. case 'search_active_microsite_users':
  180. $results = $this->getSearchActiveMicrositeUsers();
  181. break;
  182. case 'search_min_should_match':
  183. $results = $this->getSearchMinShouldMatch();
  184. break;
  185. case 'search_map':
  186. $results = $this->getSearchMap();
  187. break;
  188. default:
  189. $results = false;
  190. }
  191.  
  192. return $results;
  193. }
  194.  
  195. public function getFieldPrice($params)
  196. {
  197. if (!empty($params['price_type'])) {
  198. return get_field_price_name($params['price_type']);
  199. }
  200.  
  201. return get_field_price_name(DEFAULT_PRICE_TYPE);
  202. }
  203.  
  204. /**
  205. * Get params array.
  206. *
  207. * @return array returns an key/value array with all search params
  208. *
  209. * @author Francesc Roldán <francesc@enalquiler.com>
  210. * */
  211. public function getSearchParams()
  212. {
  213. return $this->search_params;
  214. }
  215.  
  216. /**
  217. * Set params array.
  218. *
  219. * @param array $params a full set of key/values
  220. *
  221. * @return DefaultSearchHandler
  222. *
  223. * @author Francesc Roldán <francesc@enalquiler.com>
  224. * */
  225. public function setSearchParams(array $params)
  226. {
  227. $this->search_params = $params;
  228.  
  229. return $this;
  230. }
  231.  
  232. /**
  233. * Add a param into params array.
  234. *
  235. * @param array $param a key/values array
  236. *
  237. * @return DefaultSearchHandler
  238. *
  239. * @author Francesc Roldán <francesc@enalquiler.com>
  240. * */
  241. public function addSearchParam(array $param)
  242. {
  243. $this->search_params[\key($param)] = \current($param);
  244.  
  245. return $this;
  246. }
  247.  
  248. /**
  249. * Remove a param from params array.
  250. *
  251. * @param string $paramName param name to remove
  252. *
  253. * @return DefaultSearchHandler or false if param name not exists
  254. *
  255. * @author Francesc Roldán <francesc@enalquiler.com>
  256. * */
  257. public function removeSearchParam($paramName)
  258. {
  259. if (!isset($this->search_params[$paramName])) {
  260. return false;
  261. }
  262.  
  263. unset($this->search_params[$paramName]);
  264.  
  265. return $this;
  266. }
  267.  
  268. /**
  269. * Remove all params from params array.
  270. *
  271. * @return DefaultSearchHandler
  272. *
  273. * @author Francesc Roldán <francesc@enalquiler.com>
  274. * */
  275. public function removeSearchParams()
  276. {
  277. $this->search_params = [];
  278.  
  279. return $this;
  280. }
  281.  
  282. /**
  283. * Gets the value of qb.
  284. *
  285. * @return mixed
  286. */
  287. public function getQb()
  288. {
  289. return $this->qb;
  290. }
  291.  
  292. /**
  293. * Sets the value of qb.
  294. *
  295. * @param mixed $qb the qb
  296. *
  297. * @return self
  298. */
  299. public function setQb($qb)
  300. {
  301. $this->qb = $qb;
  302.  
  303. return $this;
  304. }
  305.  
  306. public function getAggregations()
  307. {
  308. return $this->aggregations;
  309. }
  310.  
  311. public function setAggregations($aggregations): void
  312. {
  313. $this->aggregations = $aggregations;
  314. }
  315.  
  316. public function getHighlight()
  317. {
  318. return $this->highlight;
  319. }
  320.  
  321. public function setHighlight($highlight): void
  322. {
  323. $this->highlight = $highlight;
  324. }
  325.  
  326. public function getQueryType()
  327. {
  328. return $this->queryType;
  329. }
  330.  
  331. public function setQueryType($queryType): void
  332. {
  333. $this->queryType = $queryType;
  334. }
  335.  
  336. public function getParameters()
  337. {
  338. return $this->parameters;
  339. }
  340.  
  341. public function setParameters($parameters, $index): void
  342. {
  343. $this->parameters = $parameters;
  344. $this->setAggregations($parameters['elastica']['indexes'][$index]['aggregations']);
  345. $this->setHighlight($parameters['elastica']['indexes'][$index]['highlight']);
  346. $this->setQueryTypeOr();
  347. }
  348.  
  349. public function setQueryTypeOrMinShouldMatch(): void
  350. {
  351. $this->setQueryType($this->parameters['elastica']['queryType']['queryOrMinShouldMatch']);
  352. }
  353.  
  354. public function setQueryTypeOr(): void
  355. {
  356. $this->setQueryType($this->parameters['elastica']['queryType']['queryOr']);
  357. }
  358.  
  359. public function setQueryTypeAnd(): void
  360. {
  361. $this->setQueryType($this->parameters['elastica']['queryType']['queryAnd']);
  362. }
  363.  
  364. public function clearDebug(): void
  365. {
  366. $this->debug = '';
  367. }
  368.  
  369. public function executeRawPropertySearch(array $query)
  370. {
  371. $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
  372.  
  373. try {
  374. if (isset($this->search_params['debug']) && $this->search_params['debug'] && ENV != 'PROD') {
  375. die(\json_encode($query, JSON_PRETTY_PRINT));
  376. }
  377. $results = $indexInstance->search($query);
  378. } catch (\Exception $e) {
  379. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . \json_encode($query, 1) . ' ' . $e->getMessage());
  380.  
  381. return false;
  382. }
  383.  
  384. return $this->processResults($results, []);
  385. }
  386.  
  387. public function getSearchTotal()
  388. {
  389. $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
  390.  
  391. $config = [
  392. 'size' => 1,
  393. 'queryFilters' => $queryFilters,
  394. 'offset' => 0,
  395. ];
  396.  
  397. if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
  398. $config['textQuery'] = $this->search_params['query_string'];
  399. }
  400.  
  401. $results = $this->filteredSearch($config);
  402.  
  403. if (!$results instanceof ResultSet) {
  404. return 0;
  405. }
  406.  
  407. return $results->getTotalHits();
  408. }
  409.  
  410. public function getSearchResults()
  411. {
  412. $params = $this->search_params;
  413. $queryFilters = $this->getQueryFiltersToSearch($params);
  414.  
  415. $config = [
  416. 'size' => (isset($params['size']) && (int) $params['size'] > 0) ? $params['size'] : WEB_NUM_ROWS_PAGE,
  417. 'queryFilters' => $queryFilters,
  418. ];
  419.  
  420. $config = $this->setQueryAggregations($queryFilters, $config, ['closeLocations']);
  421.  
  422. if (!empty($this->search_params['fields'])) {
  423. $config['fields'] = $this->search_params['fields'];
  424. }
  425.  
  426. if (!empty($params['max_results'])) {
  427. $config['size'] = $params['max_results'];
  428. }
  429.  
  430. $config['offset'] = 0;
  431. if (isset($params['page']) && (int) ($params['page']) > 3) {
  432. $config['offset'] = ($params['page'] - 1) * WEB_NUM_ROWS_PAGE;
  433. } elseif (isset($params['offset']) && (int) ($params['offset']) > 0) {
  434. $config['offset'] = $params['offset'];
  435. }
  436.  
  437. if (empty($this->search_params['query_string'])) {
  438. $config['order'] = 'orden';
  439. $config['type_order'] = 'asc';
  440. } else {
  441. $config['textQuery'] = $this->search_params['query_string'];
  442.  
  443. if (isset($params['min_should_match']) && isset($params['cleanAnchor']) && $params['cleanAnchor'] != '') {
  444. $config['minShouldMatch'] = $params['min_should_match'];
  445. $config['textQuery'] = $params['cleanAnchor'];
  446. $this->setQueryTypeOrMinShouldMatch();
  447. }
  448. }
  449.  
  450. $order = [];
  451. if (isset($this->search_params['order_booking_online'])) {
  452. $order = $this->search_params['order_booking_online'];
  453. }
  454.  
  455. $searchParamOrderField = $this->search_params['order_field'];
  456. $searchParamTypeOrder = $this->search_params['type_order'];
  457. if (isset($searchParamOrderField) && $searchParamOrderField) {
  458. $order = $this->orderSearchByFields($searchParamOrderField, $searchParamTypeOrder, $config, $order);
  459. }
  460.  
  461. if (\count($order) > 0) {
  462. $config['order'] = $order;
  463. }
  464.  
  465. $results = $this->filteredSearch($config);
  466.  
  467. return $this->processResults($results, $config);
  468. }
  469.  
  470. public function getSearchLastProperties()
  471. {
  472. $params = $this->search_params;
  473. $queryFilters = $this->getQueryFiltersToSearch($params);
  474.  
  475. $size = WEB_NUM_ROWS_PAGE;
  476. if (isset($params['size']) && $params['size'] > 0) {
  477. $size = $params['size'];
  478. }
  479.  
  480. $config = [
  481. 'size' => $size,
  482. 'queryFilters' => $queryFilters,
  483. 'offset' => 0,
  484. 'order' => 'fec_alta',
  485. 'order_type' => 'desc',
  486. ];
  487.  
  488. $results = $this->filteredSearch($config);
  489.  
  490. return $this->processResults($results, $config);
  491. }
  492.  
  493. public function getSearchFavourites()
  494. {
  495. $params = $this->search_params;
  496. $queryFilters = $this->getQueryFiltersToSearch($params);
  497.  
  498. $size = WEB_NUM_FAVS_PAGE;
  499. if (isset($params['size']) && $params['size'] > 0) {
  500. $size = $params['size'];
  501. }
  502.  
  503. $config = [
  504. 'size' => $size,
  505. 'queryFilters' => $queryFilters,
  506. 'offset' => 0,
  507. 'order' => 'fec_alta',
  508. 'order_type' => 'desc',
  509. ];
  510.  
  511. $results = $this->filteredSearch($config);
  512.  
  513. return $this->processResults($results, $config);
  514. }
  515.  
  516. public function getSearchCloseLocations()
  517. {
  518. if (!isset($this->search_params['max_results']) || !$this->search_params['max_results']) {
  519. $this->search_params['max_results'] = 20;
  520. }
  521.  
  522. $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
  523.  
  524. if (!isset($this->search_params['search_center'])) {
  525. $lat_lon = $this->getLocationCoords($this->search_params['poblacion']);
  526. } else {
  527. $lat_lon = $this->search_params['search_center'];
  528. }
  529.  
  530. $radius = (empty($this->search_params['radius'])) ? 10 : $this->search_params['radius'];
  531.  
  532. $config = [
  533. 'offset' => 0,
  534. 'size' => $this->search_params['max_results'],
  535. 'lat_lon' => ['lat' => (float) $lat_lon['latitud'], 'lon' => (float) $lat_lon['longitud']],
  536. 'order' => ['geo_location.location'],
  537. 'radius' => $radius,
  538. ];
  539.  
  540. $config = $this->setQueryAggregations(
  541. $queryFilters,
  542. $config,
  543. ['conFoto', 'locations', 'provinces', 'districts', 'neighborhoods']
  544. );
  545.  
  546. $config['queryFilters'] = $config['closeLocations']['queryFilters'];
  547.  
  548. if (isset($this->search_params['poblacion']) && $this->search_params['poblacion']) {
  549. $config['closeLocations']['queryFilters'][] = $this->getCloseLocationsFilter(
  550. (float) $lat_lon['latitud'],
  551. (float) $lat_lon['longitud'],
  552. $radius
  553. );
  554. }
  555.  
  556. $results = $this->geoSearch($config);
  557.  
  558. return $this->processResults($results, $config);
  559. }
  560.  
  561. public function getBoostedCloseLocations()
  562. {
  563. if (!isset($this->search_params['max_results']) || !$this->search_params['max_results']) {
  564. $this->search_params['max_results'] = 15;
  565. }
  566.  
  567. if (empty($this->search_params['radius'])) {
  568. $this->search_params['radius'] = isset($this->search_params['distritos'])
  569. && \count(\explode(',', $this->search_params['distritos'])) == 1 ? 5 : 10;
  570. }
  571.  
  572. $params = $this->search_params;
  573.  
  574. $onlineBooking = isset($params['online_booking']) && (int) $params['online_booking'] === 1;
  575. unset($params['online_booking']);
  576.  
  577. $queryFilters = $this->getQueryFiltersToSearch($params);
  578.  
  579. $lat_lon = $this->removeLocationFilters($params, $queryFilters);
  580.  
  581. $config = [
  582. 'offset' => 0,
  583. 'size' => $params['max_results'],
  584. 'lat_lon' => ['lat' => (float) $lat_lon['latitud'], 'lon' => (float) $lat_lon['longitud']],
  585. 'radius' => $params['radius'],
  586. ];
  587.  
  588. if ($onlineBooking) {
  589. $config['order'][] = $this->getOnlineBookingSorting();
  590. }
  591.  
  592. if (isset($params['precio_old'])) {
  593. $config['order'][] = $this->getPriceSorting($params);
  594. }
  595.  
  596. $config['order'][] = $this->getPaymentSorting($params);
  597. $config['order'][] = 'geo_location.location';
  598.  
  599. $config = $this->setQueryAggregations(
  600. $queryFilters,
  601. $config,
  602. ['conFoto', 'locations', 'provinces', 'districts', 'neighborhoods', 'priceHistogram', 'priceHistogramOverBoundary']
  603. );
  604.  
  605. $config['queryFilters'] = $queryFilters;
  606.  
  607. if (isset($params['poblacion']) && $params['poblacion'] && isset($config['closeLocations'])) {
  608. $config['closeLocations']['queryFilters'][] = $this->getCloseLocationsFilter(
  609. (float) $lat_lon['latitud'],
  610. (float) $lat_lon['longitud'],
  611. $params['radius']
  612. );
  613. }
  614.  
  615. $results = $this->geoSearch($config);
  616.  
  617. return $this->processResults($results, $config);
  618. }
  619.  
  620. public function getSearchMinPrice()
  621. {
  622. $params = $this->search_params;
  623.  
  624. // hack para evitar mostrar pisos desde 0 euros
  625. $params['precio_min'] = 100;
  626.  
  627. $queryFilters = $this->getQueryFiltersToSearch($params);
  628.  
  629. $config = [
  630. 'size' => 1,
  631. 'queryFilters' => $queryFilters,
  632. 'offset' => 0,
  633. 'order' => $this->getFieldPrice($params),
  634. 'order_type' => 'asc',
  635. ];
  636.  
  637. if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
  638. $config['textQuery'] = $this->search_params['query_string'];
  639. }
  640.  
  641. $results = $this->filteredSearch($config);
  642. $aInfo = $this->processResults($results, $config);
  643.  
  644. return $aInfo;
  645. }
  646.  
  647. public function getSearchMinShouldMatch()
  648. {
  649. $params = $this->search_params;
  650. $queryFilters = $this->getQueryFiltersToSearch($params);
  651.  
  652. $this->setQueryTypeOrMinShouldMatch();
  653.  
  654. $config = [
  655. 'size' => 1,
  656. 'queryFilters' => $queryFilters,
  657. 'offset' => 0,
  658. 'minShouldMatch' => $params['minShouldMatch'] ?? 1,
  659. ];
  660. if (!empty($this->search_params['query_string'])) {
  661. $config['textQuery'] = $this->search_params['query_string'];
  662. }
  663.  
  664. $results = $this->filteredSearch($config);
  665.  
  666. return $results ? $results->getTotalHits() : 0;
  667. }
  668.  
  669. public function getSearchCategoriesCounts()
  670. {
  671. $queryFilters = [];
  672.  
  673. $locale = $this->getEnvironment()->getCurrentLanguage();
  674.  
  675. $queryBuilder = new ElasticaQueryBuilder();
  676. $queryBuilder->aggregation([
  677. 'name' => 'categories',
  678. 'type' => 'terms',
  679. 'aggs_type' => 'terms',
  680. 'size' => 200000,
  681. 'order' => '_term',
  682. 'order_type' => 'desc',
  683. 'filters' => $queryFilters,
  684. 'field' => 'nombre_categoria_slug_' . $locale . '.raw',
  685. ]);
  686.  
  687. $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
  688.  
  689. try {
  690. $queryResults = $indexInstance->search($queryBuilder->getQuery());
  691. $aggregations = $queryResults->getAggregations();
  692.  
  693. $results = [];
  694. foreach ($aggregations as $key => $aggregation) {
  695. foreach ($aggregation['buckets'] as $k => $category) {
  696. $item = \explode('|', $category['key']);
  697. if ($item[1] > 0) {
  698. $results[$item[1]]['doc_count'] = $category['doc_count'];
  699. $results[$item[1]]['id'] = $item[1];
  700. $results[$item[1]]['category'] = TextUtilities::reduceUTF8($item[0]);
  701. }
  702. }
  703. }
  704.  
  705. return $results;
  706. } catch (\Exception $e) {
  707. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  708.  
  709. return false;
  710. }
  711. }
  712.  
  713. public function getSearchProvince()
  714. {
  715. if (!isset($this->search_params['max_results']) || !$this->search_params['max_results']) {
  716. $this->search_params['max_results'] = 150;
  717. }
  718. //TODO: use search_params everywhere
  719. $params = $this->search_params;
  720. $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
  721.  
  722. $config = [
  723. 'offset' => 0,
  724. 'size' => $this->search_params['max_results'],
  725. ];
  726.  
  727. //$config = $this->_setQueryAggregations($queryFilters, $config, array('conFoto'));
  728.  
  729. $config['queryFilters'] = $this->removeFilters(
  730. $queryFilters,
  731. ['fk_id_tbl_poblaciones', 'or_distritos', 'or_barrios']
  732. );
  733.  
  734. if (empty($this->search_params['query_string'])) {
  735. $config['order'] = 'orden';
  736. $config['order_type'] = 'asc';
  737. } else {
  738. $config['textQuery'] = $this->search_params['query_string'];
  739. }
  740.  
  741. if (isset($this->search_params['order_field']) && $this->search_params['order_field']) {
  742. $config['order'] = \str_replace('alquiler ', '', $this->search_params['order_field']);
  743. }
  744.  
  745. if (isset($this->search_params['type_order']) && $this->search_params['type_order']) {
  746. $config['order_type'] = \str_replace('alquiler ', '', $this->search_params['type_order']);
  747. }
  748.  
  749. $results = $this->filteredSearch($config);
  750.  
  751. $aInfo = $this->processResults($results, $config);
  752.  
  753. return $aInfo;
  754. }
  755.  
  756. public function getSearchBoostedProperties()
  757. {
  758. $config = [
  759. 'offset' => 0,
  760. 'size' => $this->search_params['max_results'],
  761. ];
  762.  
  763. $price_type_field = $this->getFieldPrice($this->search_params);
  764. $config['order'][] = [
  765. 'order' => [
  766. '_script' => [
  767. 'script' => '(doc[\'foto\'].value == 0 || doc[\'fk_id_tbl_distritos\'].value != districts)?70:'
  768. . '((doc[\'fk_id_tbl_barrios\'].value != neighborhoods)?((doc[\'boosting_multirequest\'].value == 1)?5:50):0) + '
  769. . '((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == 1)?0:'
  770. . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == 0)?10:'
  771. . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 1)?20:'
  772. . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == -1)?60:'
  773. . ' ((doc[\'pago\'].value == 0 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 1)?30:'
  774. . ' ((doc[\'pago\'].value == 0 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2)?40:50)'
  775. . ' )'
  776. . ' )'
  777. . ' )'
  778. . ' )'
  779. . ')',
  780. 'type' => 'number',
  781. 'order' => 'asc',
  782. 'params' => [
  783. 'districts' => $this->search_params['distritos'],
  784. 'neighborhoods' => $this->search_params['barrios'],
  785. ],
  786. ],
  787. ],
  788. ];
  789.  
  790. $config['order'][] = [
  791. 'order' => [
  792. '_script' => [
  793. 'script' => 'abs(doc[\'' . $price_type_field . '\'].value - ' . $price_type_field . ')',
  794. 'type' => 'number',
  795. 'order' => 'asc',
  796. 'params' => [
  797. $price_type_field => (float) ($this->search_params['precio']),
  798. ],
  799. ],
  800. ],
  801. ];
  802.  
  803. $config['order'][] = [
  804. 'order' => [
  805. '_script' => [
  806. 'script' => 'abs(doc[\'num_habitaciones\'].value - rooms)',
  807. 'type' => 'number',
  808. 'order' => 'asc',
  809. 'params' => [
  810. 'rooms' => (int) ($this->search_params['habitaciones']),
  811. ],
  812. ],
  813. ],
  814. ];
  815. unset($this->search_params['precio'], $this->search_params['distritos'], $this->search_params['barrios'], $this->search_params['habitaciones']);
  816.  
  817.  
  818.  
  819.  
  820. $config['queryFilters'] = $this->getQueryFiltersToSearch($this->search_params);
  821.  
  822. $results = $this->filteredSearch($config);
  823.  
  824. return $this->processResults($results, $config);
  825. }
  826.  
  827. public function getSearchExpertAgencyProperties()
  828. {
  829. $params = $this->search_params;
  830. $params['con_foto'] = 1;
  831.  
  832. $queryFilters = $this->getQueryFiltersToSearch($params);
  833.  
  834. $config = [
  835. 'size' => (isset($params['size']) && (int) ($params['size']) > 0) ? $params['size'] : WEB_NUM_ROWS_PAGE,
  836. 'queryFilters' => $queryFilters,
  837. ];
  838.  
  839. if (!empty($params['max_results'])) {
  840. $config['size'] = $params['max_results'];
  841. }
  842.  
  843. if (!empty($params['precio_max']) && !empty($params['habitaciones'])) {
  844. $config['order'][] = [
  845. 'order' => [
  846. '_script' => [
  847. 'script' => '(abs(doc[\'' . $this->getFieldPrice($params) . '\'].value - ' . $params['precio_max'] . ') + ((doc[\'num_habitaciones\'].value >= ' . $params['habitaciones'] . ') ? 1 : 0))',
  848. 'type' => 'number',
  849. 'order' => 'desc',
  850. ],
  851. ],
  852. ];
  853. } elseif (!empty($params['precio_max'])) {
  854. $config['order'][] = [
  855. 'order' => [
  856. '_script' => [
  857. 'script' => '(abs(doc[\'' . $this->getFieldPrice($params) . '\'].value - ' . $params['precio_max'] . '))',
  858. 'type' => 'number',
  859. 'order' => 'desc',
  860. ],
  861. ],
  862. ];
  863. } elseif (!empty($params['habitaciones'])) {
  864. $config['order'][] = [
  865. 'order' => [
  866. '_script' => [
  867. 'script' => '((doc[\'num_habitaciones\'].value >= ' . $params['habitaciones'] . ') ? 1 : 0)',
  868. 'type' => 'number',
  869. 'order' => 'desc',
  870. ],
  871. ],
  872. ];
  873. } else {
  874. $config['order'][] = ['order' => 'orden', 'order_type' => 'asc'];
  875. }
  876.  
  877. $results = $this->filteredSearch($config);
  878.  
  879. return $this->processResults($results, $config);
  880. }
  881.  
  882. public function getSearchAlertProperties()
  883. {
  884. $config = [
  885. 'offset' => 0,
  886. 'size' => (isset($this->search_params['max_results'])) ? $this->search_params['max_results'] : 10,
  887. ];
  888.  
  889. if (isset($this->search_params['order_field'])) {
  890. if (\is_array($this->search_params['order_field'])) {
  891. foreach ($this->search_params['order_field'] as $k => $order_field) {
  892. $config['order'][] = ['order' => $order_field, 'order_type' => (isset($this->search_params['order_type'][$k])) ? $this->search_params['order_type'][$k] : 'asc'];
  893. }
  894. } else {
  895. $config['order'] = $this->search_params['order_field'];
  896. $config['order_type'] = 'asc';
  897.  
  898. if (isset($this->search_params['order_type'])) {
  899. $config['order_type'] = $this->search_params['order_type'];
  900. }
  901. }
  902.  
  903. unset($this->search_params['order_field'], $this->search_params['order_type']);
  904. }
  905.  
  906. $config['queryFilters'] = $this->getQueryFiltersToSearch($this->search_params);
  907.  
  908. $results = $this->filteredSearch($config);
  909.  
  910. return $this->processResults($results, $config);
  911. }
  912.  
  913. public function getSearchRelatedProperties()
  914. {
  915. $config = [
  916. 'offset' => 0,
  917. 'size' => $this->search_params['max_results'],
  918. ];
  919.  
  920. if (isset($this->search_params['distritos'])) {
  921. $districts = [];
  922. if (\is_array($this->search_params['distritos'])) {
  923. foreach ($this->search_params['distritos'] as $district) {
  924. $districts[] = 'doc[\'fk_id_tbl_distritos\'].value == ' . $district;
  925. }
  926. } else {
  927. $districts[] = 'doc[\'fk_id_tbl_distritos\'].value == ' . $this->search_params['distritos'];
  928. }
  929.  
  930. $config['order'][] = [
  931. 'order' => [
  932. '_script' => [
  933. 'script' => \implode(' || ', $districts) . '?1:0',
  934. 'type' => 'number',
  935. 'order' => 'desc',
  936. ],
  937. ],
  938. ];
  939. }
  940.  
  941. $config['order'][] = [
  942. 'order' => [
  943. '_script' => [
  944. 'script' => 'doc[\'fk_id_tbl_poblaciones\'].value == ' . $this->search_params['poblacion'] . '?1:0',
  945. 'type' => 'number',
  946. 'order' => 'desc',
  947. ],
  948. ],
  949. ];
  950.  
  951. $config['order'][] = [
  952. 'order' => [
  953. '_script' => [
  954. 'script' => '(doc[\'' . $this->getFieldPrice($this->search_params) . '\'].value <= ' . $this->search_params['precio_max'] . ' && doc[\'' . $this->getFieldPrice($this->search_params) . '\'].value >= ' . $this->search_params['precio_min'] . ')?1:0',
  955. 'type' => 'number',
  956. 'order' => 'desc',
  957. ],
  958. ],
  959. ];
  960.  
  961. $config['order'][] = [
  962. 'order' => [
  963. '_script' => [
  964. 'script' => 'doc[\'foto\'].value > 0?1:0',
  965. 'type' => 'number',
  966. 'order' => 'desc',
  967. ],
  968. ],
  969. ];
  970.  
  971. if (!isset($this->search_params['distritos'])) {
  972. //$config['order'][] = array('order' => 'orden', 'order_type' => 'asc');
  973. $config['order'][] = ['order' => ['orden' => ['order' => 'asc']]];
  974. }
  975.  
  976. unset($this->search_params['distritos'], $this->search_params['poblacion'], $this->search_params['barrios'], $this->search_params['precio_min'], $this->search_params['precio_max']);
  977.  
  978.  
  979.  
  980.  
  981.  
  982. $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
  983.  
  984. $config['queryFilters'] = $queryFilters;
  985.  
  986. $results = $this->filteredSearch($config);
  987.  
  988. $aInfo = $this->processResults($results, $config);
  989.  
  990. $aDO = [];
  991. if (\count($aInfo['searchResults'])) {
  992. foreach ($aInfo['searchResults'] as $res) {
  993. $res['url'] = $this->getUrl($res);
  994. $res['anchor'] = $res['titulo_var'];
  995. $res['barrio'] = $res['nombre_barrio'];
  996. $aDO['pk_' . $res['id']] = $res;
  997. }
  998. }
  999.  
  1000. return $aDO;
  1001. }
  1002.  
  1003. public function getSearchActiveMicrositeUsers()
  1004. {
  1005. $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
  1006.  
  1007. $queryBuilder = new ElasticaQueryBuilder();
  1008. $queryBuilder->filterAnd($queryFilters);
  1009. $queryBuilder->aggregation(['name' => 'users', 'type' => 'filter', 'aggs_type' => 'terms', 'size' => 200000,
  1010. 'order' => '_term', 'order_type' => 'desc', 'filters' => $queryFilters, 'field' => 'fk_id_tbl_usuarios', ]);
  1011.  
  1012. $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
  1013.  
  1014. $users = [];
  1015. try {
  1016. $queryResults = $indexInstance->search($queryBuilder->getQuery());
  1017. $aggregations = $queryResults->getAggregations();
  1018. foreach ($aggregations['users']['items']['buckets'] as $userInfo) {
  1019. $users[] = $userInfo['key'];
  1020. }
  1021. } catch (\Exception $e) {
  1022. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1023. }
  1024.  
  1025. return $users;
  1026. }
  1027.  
  1028. public function getSearchApiIphone()
  1029. {
  1030. $params = $this->search_params;
  1031. $queryFilters = $this->getQueryFiltersToSearch($params);
  1032.  
  1033. $config = [
  1034. 'size' => (isset($params['size']) && (int) ($params['size']) > 0) ? $params['size'] : WEB_NUM_ROWS_PAGE,
  1035. 'queryFilters' => $queryFilters,
  1036. ];
  1037.  
  1038. if (isset($params['lat_lon'])) {
  1039. $config['lat_lon'] = $params['lat_lon'];
  1040. }
  1041.  
  1042. if (!isset($this->search_params['radius']) || !$this->search_params['radius']) {
  1043. $this->search_params['radius'] = 10;
  1044. }
  1045.  
  1046. $config = $this->setQueryAggregations($queryFilters, $config);
  1047.  
  1048. if (!empty($this->search_params['fields'])) {
  1049. $config['fields'] = $this->search_params['fields'];
  1050. }
  1051.  
  1052. if (!empty($params['max_results'])) {
  1053. $config['size'] = $params['max_results'];
  1054. }
  1055.  
  1056. if (isset($params['page']) && (int) ($params['page']) > 0) {
  1057. $config['offset'] = ($params['page'] - 1) * WEB_NUM_ROWS_PAGE;
  1058. } else {
  1059. $config['offset'] = 0;
  1060. }
  1061.  
  1062. if (isset($this->search_params['poblacion']) && $this->search_params['poblacion']) {
  1063. $lat_lon = $this->getLocationCoords($this->search_params['poblacion']);
  1064. $config['closeLocations']['queryFilters'][] = $this->getCloseLocationsFilter(
  1065. (float) $lat_lon['latitud'],
  1066. (float) $lat_lon['longitud'],
  1067. $this->search_params['radius']
  1068. );
  1069. }
  1070.  
  1071. if (empty($this->search_params['query_string'])) {
  1072. $config['order'] = 'orden';
  1073. $config['order_type'] = 'asc';
  1074. } else {
  1075. $config['textQuery'] = $this->search_params['query_string'];
  1076. }
  1077.  
  1078. if (isset($this->search_params['order_field']) && $this->search_params['order_field']) {
  1079. $config['order'] = \str_replace('alquiler ', '', $this->search_params['order_field']);
  1080. }
  1081.  
  1082. if (isset($this->search_params['type_order']) && $this->search_params['type_order']) {
  1083. $config['order_type'] = \str_replace('alquiler ', '', $this->search_params['type_order']);
  1084. }
  1085.  
  1086. if (isset($config['lat_lon'])) {
  1087. $results = $this->geoSearch($config);
  1088. } else {
  1089. $results = $this->filteredSearch($config);
  1090. }
  1091.  
  1092. return $this->processResults($results, $config);
  1093. }
  1094.  
  1095. public function getProvinceCounts()
  1096. {
  1097. $locale = $this->getEnvironment()->getCurrentLanguage();
  1098. $queryFilters = [];
  1099.  
  1100. $field = 'nombre_prov_slug';
  1101.  
  1102. if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
  1103. $field .= '_' . $locale;
  1104. }
  1105.  
  1106. $field .= '.raw';
  1107.  
  1108. $queryBuilder = new ElasticaQueryBuilder();
  1109. $queryBuilder->aggregation([
  1110. 'name' => 'provincias',
  1111. 'type' => 'terms',
  1112. 'aggs_type' => 'terms',
  1113. 'size' => 1000,
  1114. 'order' => '_term',
  1115. 'order_type' => 'asc',
  1116. 'filters' => $queryFilters,
  1117. 'field' => $field,
  1118. ]);
  1119.  
  1120. $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
  1121.  
  1122. try {
  1123. $queryResults = $indexInstance->search($queryBuilder->getQuery());
  1124.  
  1125. $aggregations = $queryResults->getAggregations();
  1126.  
  1127. $results = [];
  1128. $results['totals'] = $queryResults->getTotalHits();
  1129. foreach ($aggregations as $key => $aggregation) {
  1130. foreach ($aggregation['buckets'] as $k => $province) {
  1131. $item = \explode('|', $province['key']);
  1132. if ($item[2] > 0) {
  1133. $results[$key]['items'][$item[2]]['doc_count'] = $province['doc_count'];
  1134. $results[$key]['items'][$item[2]]['id'] = $item[2];
  1135. $results[$key]['items'][$item[2]]['name'] = TextUtilities::reduceUTF8($item[1]);
  1136. }
  1137. }
  1138. }
  1139.  
  1140. return $results;
  1141. } catch (\Exception $e) {
  1142. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1143.  
  1144. return false;
  1145. }
  1146. }
  1147.  
  1148. public function getSuggestProvincesCounts()
  1149. {
  1150. $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
  1151.  
  1152. $config = [
  1153. 'queryFilters' => $queryFilters,
  1154. ];
  1155.  
  1156. if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
  1157. $config['textQuery'] = $this->search_params['query_string'];
  1158. }
  1159.  
  1160. $excludes = [];
  1161. $this->aggregations['provinces']['exclude'] = [];
  1162.  
  1163. if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
  1164. foreach ($this->languages() as $language) {
  1165. $this->aggregations['provinces_' . $language]['exclude'] = [];
  1166. $excludes[] = 'locations_' . $language;
  1167. }
  1168. }
  1169.  
  1170. $config = $this->setQueryAggregations(
  1171. $queryFilters,
  1172. $config,
  1173. \array_merge(
  1174. $excludes,
  1175. ['locations', 'conFoto', 'closeLocations', 'districts', 'neighborhoods', 'priceHistogram', 'priceHistogramOverBoundary']
  1176. )
  1177. );
  1178.  
  1179. $results = $this->aggregationSearch($config);
  1180.  
  1181. return $this->processCounts($results, $config);
  1182. }
  1183.  
  1184. public function getSuggestCitiesCounts()
  1185. {
  1186. $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
  1187.  
  1188. $config = [
  1189. 'queryFilters' => $queryFilters,
  1190. ];
  1191.  
  1192. if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
  1193. $config['textQuery'] = $this->search_params['query_string'];
  1194. }
  1195.  
  1196. $excludes = [];
  1197. $this->aggregations['locations']['exclude'] = [];
  1198.  
  1199. if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
  1200. foreach ($this->languages() as $language) {
  1201. $this->aggregations['locations_' . $language]['exclude'] = [];
  1202. $excludes[] = 'provinces_' . $language;
  1203. }
  1204. }
  1205.  
  1206. $config = $this->setQueryAggregations(
  1207. $queryFilters,
  1208. $config,
  1209. \array_merge(
  1210. $excludes,
  1211. ['provinces', 'conFoto', 'closeLocations', 'districts', 'neighborhoods', 'priceHistogram', 'priceHistogramOverBoundary']
  1212. )
  1213. );
  1214.  
  1215. $results = $this->aggregationSearch($config);
  1216.  
  1217. return $this->processCounts($results, $config);
  1218. }
  1219.  
  1220. public function getSuggestDistrictsCounts()
  1221. {
  1222. $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
  1223.  
  1224. $config = [
  1225. 'queryFilters' => $queryFilters,
  1226. ];
  1227.  
  1228. if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
  1229. $config['textQuery'] = $this->search_params['query_string'];
  1230. }
  1231.  
  1232. $this->aggregations['districts']['exclude'] = [];
  1233.  
  1234. $config = $this->setQueryAggregations(
  1235. $queryFilters,
  1236. $config,
  1237. ['provinces', 'locations', 'conFoto', 'closeLocations', 'neighborhoods', 'priceHistogram', 'priceHistogramOverBoundary']
  1238. );
  1239.  
  1240. $results = $this->aggregationSearch($config);
  1241.  
  1242. return $this->processCounts($results, $config);
  1243. }
  1244.  
  1245. public function getSuggestNeighborhoodsCounts()
  1246. {
  1247. $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
  1248.  
  1249. $config = [
  1250. 'queryFilters' => $queryFilters,
  1251. ];
  1252.  
  1253. if (isset($this->search_params['home']) && $this->search_params['home']) {
  1254. $config['home'] = true;
  1255. }
  1256.  
  1257. $config['url'] = 0;
  1258.  
  1259. if (isset($this->search_params['url']) && $this->search_params['url']) {
  1260. $config['url'] = 1;
  1261. }
  1262.  
  1263. if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
  1264. $config['textQuery'] = $this->search_params['query_string'];
  1265. }
  1266.  
  1267. $this->aggregations['neighborhoods']['exclude'] = [];
  1268.  
  1269. $config = $this->setQueryAggregations(
  1270. $queryFilters,
  1271. $config,
  1272. ['provinces', 'locations', 'conFoto', 'closeLocations', 'districts', 'priceHistogram', 'priceHistogramOverBoundary']
  1273. );
  1274.  
  1275. $results = $this->aggregationSearch($config);
  1276.  
  1277. return $this->processCounts($results, $config);
  1278. }
  1279.  
  1280. public function getSuggestHome()
  1281. {
  1282. $queryBuilder = new ElasticaQueryBuilder();
  1283. $queryBuilder->suggest($this->search_params);
  1284.  
  1285. $results = $this->executeSuggest($queryBuilder);
  1286.  
  1287. return $this->processSuggests($results);
  1288. }
  1289.  
  1290. //Función de la que se nutre el sitemap
  1291. public function getSearchCapitalProvinceCounts()
  1292. {
  1293. $params = $this->search_params;
  1294.  
  1295. $queryFilters = [];
  1296.  
  1297. if (isset($params['tipo']) && $params['tipo'] != 1) {
  1298. $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_categorias', 'value' => ['gte' => $params['tipo'],
  1299. 'lte' => $params['tipo'], ]];
  1300. }
  1301.  
  1302. if (isset($params['province_capital'])) {
  1303. $queryFilters[] = ['type' => 'range', 'field' => 'province_capital', 'value' => ['gte' => $params['province_capital']]];
  1304. }
  1305.  
  1306. $queryBuilder = new ElasticaQueryBuilder();
  1307. $queryBuilder->aggregation(['name' => 'ciudades', 'type' => 'filter', 'aggs_type' => 'terms', 'field' => 'city.raw',
  1308. 'size' => 1000, 'order' => '_term', 'order_type' => 'asc', 'filters' => $queryFilters, 'field' => 'nombre_pob_slug.raw', ]);
  1309.  
  1310. $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
  1311.  
  1312. try {
  1313. $queryResults = $indexInstance->search($queryBuilder->getQuery());
  1314. $aggregations = $queryResults->getAggregations();
  1315.  
  1316. $results = [];
  1317.  
  1318. foreach ($aggregations as $key => $aggregation) {
  1319. foreach ($aggregation['items']['buckets'] as $k => $city) {
  1320. $item = \explode('|', $city['key']);
  1321. $results[$item[2]]['doc_count'] = $city['doc_count'];
  1322. $results[$item[2]]['fk_id_tbl_poblaciones'] = $item[2];
  1323. $results[$item[2]]['nombre_poblacion'] = TextUtilities::reduceUTF8($item[1]);
  1324. $results[$item[2]]['fk_id_tbl_provincias'] = $item[3];
  1325. }
  1326. }
  1327.  
  1328. return $results;
  1329. } catch (\Exception $e) {
  1330. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1331.  
  1332. return false;
  1333. }
  1334. }
  1335.  
  1336. //Función de la que se nutre el search1
  1337. public function getCityCountsByProvince()
  1338. {
  1339. $params = $this->search_params;
  1340.  
  1341. $queryFilters = [];
  1342.  
  1343. if (isset($params['tipo']) && $params['tipo'] != 1) {
  1344. $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_categorias', 'value' => ['gte' => $params['tipo'],
  1345. 'lte' => $params['tipo'], ]];
  1346. }
  1347.  
  1348. if (isset($params['con_foto'])) {
  1349. $queryFilters[] = ['type' => 'range', 'field' => 'foto', 'value' => ['gte' => 1]];
  1350. }
  1351.  
  1352. if (isset($params['precio_max'])) {
  1353. $queryFilters[] = ['type' => 'range', 'field' => $this->getFieldPrice($params), 'value' => ['lte' => $params['precio_max']]];
  1354. }
  1355.  
  1356. if (isset($params['amueblado'])) {
  1357. if ($params['amueblado'] == 2) {
  1358. $queryFilters[] = ['type' => 'range', 'field' => 'amueblado', 'value' => ['lte' => 0]];
  1359. } else {
  1360. $queryFilters[] = ['type' => 'range', 'field' => 'amueblado', 'value' => ['gte' => $params['amueblado'],
  1361. 'lte' => $params['amueblado'], ]];
  1362. }
  1363. }
  1364.  
  1365. if (isset($params['habitaciones'])) {
  1366. $queryFilters[] = ['type' => 'range', 'field' => 'num_habitaciones', 'value' => ['gte' => $params['habitaciones']]];
  1367. }
  1368.  
  1369. if (isset($params['provincia'])) {
  1370. $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_provincias', 'value' => ['gte' => $params['provincia'],
  1371. 'lte' => $params['provincia'], ]];
  1372. }
  1373.  
  1374. $queryBuilder = new ElasticaQueryBuilder();
  1375. $queryBuilder->aggregation(['name' => 'ciudades', 'type' => 'filter', 'aggs_type' => 'terms', 'field' => 'city.raw',
  1376. 'size' => 1000, 'order' => '_term', 'order_type' => 'asc', 'filters' => $queryFilters, 'field' => 'nombre_pob_slug.raw', ])
  1377. ->aggregation(['name' => 'top_ciudades', 'type' => 'filter', 'aggs_type' => 'terms', 'field' => 'city.raw',
  1378. 'size' => 5, 'order' => '_count', 'order_type' => 'desc', 'filters' => $queryFilters, 'field' => 'nombre_pob_slug.raw', ]);
  1379.  
  1380. $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
  1381.  
  1382. try {
  1383. $queryResults = $indexInstance->search($queryBuilder->getQuery());
  1384. $aggregations = $queryResults->getAggregations();
  1385.  
  1386. $results = [];
  1387. $results['ciudades']['totals'] = $aggregations['ciudades']['doc_count'];
  1388. $results['top_ciudades']['totals'] = $aggregations['top_ciudades']['doc_count'];
  1389.  
  1390. foreach ($aggregations as $key => $aggregation) {
  1391. foreach ($aggregation['items']['buckets'] as $k => $city) {
  1392. $item = \explode('|', $city['key']);
  1393. $results[$key]['items'][$item[2]]['total_inmuebles'] = $city['doc_count'];
  1394. $results[$key]['items'][$item[2]]['fk_id_tbl_poblaciones'] = $item[2];
  1395. $results[$key]['items'][$item[2]]['nombre_pob'] = TextUtilities::reduceUTF8($item[1]);
  1396. $results[$key]['items'][$item[2]]['fk_id_tbl_provincias'] = $params['provincia'];
  1397. }
  1398. }
  1399.  
  1400. return $results;
  1401. } catch (\Exception $e) {
  1402. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1403.  
  1404. return false;
  1405. }
  1406. }
  1407.  
  1408. public function getPropertyNavigation()
  1409. {
  1410. $params = $this->search_params;
  1411. $queryFilters = $this->getQueryFiltersToSearch($params);
  1412.  
  1413. $config = [
  1414. 'size' => WEB_NUM_ROWS_PAGE + 2,
  1415. 'queryFilters' => $queryFilters,
  1416. ];
  1417.  
  1418. $config['offset'] = $params['offset'];
  1419.  
  1420. //Si nos encontramos en el primer resultado de una paginación retamos al offset una posición
  1421. //para poder obtener el resultado anterior del listado.
  1422. if ($config['offset'] > 0 && ($config['offset'] % WEB_NUM_ROWS_PAGE) === 0) {
  1423. --$config['offset'];
  1424. }
  1425.  
  1426. if (!empty($this->search_params['fields'])) {
  1427. $config['fields'] = $this->search_params['fields'];
  1428. }
  1429.  
  1430. if (empty($this->search_params['query_string'])) {
  1431. $config['order'] = 'orden';
  1432. $config['order_type'] = 'asc';
  1433. } else {
  1434. $config['textQuery'] = $this->search_params['query_string'];
  1435. }
  1436.  
  1437. if (!empty($this->search_params['order_field'])) {
  1438. $config['order'] = \str_replace('alquiler ', '', $this->search_params['order_field']);
  1439. }
  1440.  
  1441. if (!empty($this->search_params['type_order'])) {
  1442. $config['order_type'] = \str_replace('alquiler ', '', $this->search_params['type_order']);
  1443. }
  1444.  
  1445. if (isset($this->search_params['order_booking_online'])) {
  1446. $config['order'] = $this->search_params['order_booking_online'];
  1447. unset($config['order_type']);
  1448. }
  1449.  
  1450. $search = $this->filteredSearch($config);
  1451. $results = $this->processResults($search, $config);
  1452.  
  1453. $total = $results['total'];
  1454. $id = $params['id'];
  1455. $pos = ($params['offset'] < 0) ? 0 : $params['offset'];
  1456. $docs = $results['searchResults'];
  1457.  
  1458. while (\key($docs) != $id) {
  1459. if (\next($docs) === false) {
  1460. \end($docs);
  1461. break;
  1462. }
  1463. ++$pos;
  1464. }
  1465.  
  1466. if (($DO_anterior = \prev($docs)) === false) {
  1467. \reset($docs);
  1468. $DO_siguiente = \next($docs);
  1469. } else {
  1470. \next($docs);
  1471. $DO_siguiente = \next($docs);
  1472. }
  1473.  
  1474. return ['total' => $total, 'position' => $pos, 'prev' => $DO_anterior, 'next' => $DO_siguiente];
  1475. }
  1476.  
  1477. public function getSearchMap()
  1478. {
  1479. $params = $this->search_params;
  1480.  
  1481. $queryFilters = $this->getQueryFiltersToSearch($params);
  1482.  
  1483. $config = [
  1484. 'queryFilters' => $queryFilters,
  1485. 'geoGrid' => [],
  1486. ];
  1487.  
  1488. $results = $this->mapSearch($config);
  1489.  
  1490. return $this->processResults($results, $config);
  1491. }
  1492.  
  1493. public function getQueryFilters($params)
  1494. {
  1495. return $this->getQueryFiltersToSearch($params);
  1496. }
  1497.  
  1498. public function getFilterHackMinPrecio($precio_max)
  1499. {
  1500. include_once PATH_SRC . 'data/daoprog/DAOProg_tbl_filtro_precio.class.php';
  1501. $DAOFiltroPrecio = new \DAOProg_tbl_filtro_precio();
  1502. $DAOFiltroPrecio->selectAllFor(
  1503. DEFAULT_PRICE_TYPE,
  1504. "precio< '" . $precio_max . "' AND indexable = 1 ",
  1505. 'precio DESC',
  1506. 0,
  1507. 1
  1508. );
  1509. if (\count($DAOFiltroPrecio->aDO) == 1) {
  1510. $precioMin = \current($DAOFiltroPrecio->aDO);
  1511.  
  1512. return $precioMin['precio'];
  1513. }
  1514.  
  1515. return 0;
  1516. }
  1517.  
  1518. public function getEnvironment()
  1519. {
  1520. if (null === $this->environment) {
  1521. $this->environment = Environment::getInstance();
  1522. }
  1523.  
  1524. return $this->environment;
  1525. }
  1526.  
  1527. /**
  1528. * @param array $searchParams
  1529. *
  1530. * @return array
  1531. */
  1532. protected function getPriceSorting(array $searchParams)
  1533. {
  1534. $searchParams = $this->search_params;
  1535. $price_type_field = $this->getFieldPrice($searchParams);
  1536.  
  1537. $script = '((doc[\'' . $price_type_field . '\'].value > ' . $searchParams['precio_old'] . ' && doc[\'fk_id_tbl_poblaciones\'].value == ' . $searchParams['poblacion'] . ' )?0:1)';
  1538.  
  1539. if (isset($searchParams['distritos']) && !\strpos(
  1540. $searchParams['distritos'],
  1541. ','
  1542. ) && $searchParams['distritos'] != 0
  1543. ) {
  1544. $script = '((doc[\'' . $price_type_field . '\'].value > ' . $searchParams['precio_old'] . ' && doc[\'fk_id_tbl_distritos\'].value == ' . $searchParams['distritos'] . ' )?0:1)';
  1545. }
  1546.  
  1547. $script .= ' + rint(((doc[\'' . $price_type_field . '\'].value - ' . $searchParams['precio_old'] . ') / ' . $searchParams['precio_old'] . ') * 100) / 100';
  1548.  
  1549. $sorting = [
  1550. '_script' => [
  1551. 'script' => $script,
  1552. 'type' => 'number',
  1553. 'order' => 'asc',
  1554. ],
  1555. ];
  1556.  
  1557. return $sorting;
  1558. }
  1559.  
  1560. /**
  1561. * @return array
  1562. */
  1563. protected function getOnlineBookingSorting()
  1564. {
  1565. $sorting = [
  1566. '_script' => [
  1567. 'script' => "(doc['booking_online'].value == 1) ? 0: 1",
  1568. 'type' => 'number',
  1569. 'order' => 'asc',
  1570. ],
  1571. ];
  1572.  
  1573. return $sorting;
  1574. }
  1575.  
  1576. /**
  1577. * @param $lat
  1578. * @param $lon
  1579. * @param $radius
  1580. *
  1581. * @return mixed
  1582. */
  1583. protected function getCloseLocationsFilter($lat, $lon, $radius)
  1584. {
  1585. if (!isset($radius) || empty($radius) || $radius < 0) {
  1586. $radius = 10;
  1587. }
  1588.  
  1589. $filter = [
  1590. 'type' => 'geo_distance',
  1591. 'field' => 'geo_location.location',
  1592. 'value' => [
  1593. 'distance' => $radius . 'km',
  1594. 'geo_location.location' => [
  1595. 'lat' => $lat,
  1596. 'lon' => $lon,
  1597. ],
  1598. ],
  1599. ];
  1600.  
  1601. return $filter;
  1602. }
  1603.  
  1604. /**
  1605. * @params $searchParams
  1606. *
  1607. * @param $queryFilters
  1608. *
  1609. * @return array
  1610. */
  1611. protected function removeLocationFilters($searchParams, &$queryFilters)
  1612. {
  1613. if (isset($searchParams['distritos']) && \count(\explode(',', $searchParams['distritos'])) == 1) {
  1614. $lat_lon = $this->getDistrictCoords();
  1615. foreach ($queryFilters as $key => $value) {
  1616. if ($value['field'] == 'or_distritos' || $value['field'] == 'or_barrios') {
  1617. unset($queryFilters[$key]);
  1618. }
  1619. }
  1620. } else {
  1621. $lat_lon = $this->getLocationCoords();
  1622. foreach ($queryFilters as $key => $value) {
  1623. if ($value['field'] == 'or_distritos' || $value['field'] == 'or_barrios' || $value['field'] == 'fk_id_tbl_poblaciones') {
  1624. unset($queryFilters[$key]);
  1625. }
  1626. }
  1627. }
  1628.  
  1629. return $lat_lon;
  1630. }
  1631.  
  1632. /**
  1633. * @param $params
  1634. *
  1635. * @return mixed
  1636. */
  1637. protected function getPaymentSorting($params)
  1638. {
  1639. if (isset($params['distritos'])) {
  1640. if (!\is_array($params['distritos'])) {
  1641. $aDistritos = \explode(',', $params['distritos']);
  1642. } else {
  1643. $aDistritos = $params['distritos'];
  1644. }
  1645.  
  1646. $aCondDistritos = [];
  1647. foreach ($aDistritos as $distrito) {
  1648. $aCondDistritos[] = "doc['fk_id_tbl_distritos'].value != " . $distrito;
  1649. }
  1650.  
  1651. $condDistritos = \implode(' && ', $aCondDistritos);
  1652. } else {
  1653. $condDistritos = "doc['fk_id_tbl_distritos'].value != 0";
  1654. }
  1655.  
  1656. if (isset($params['barrios'])) {
  1657. if (!\is_array($params['barrios'])) {
  1658. $aBarrios = \explode(',', $params['barrios']);
  1659. } else {
  1660. $aBarrios = $params['barrios'];
  1661. }
  1662.  
  1663. $aCondBarrios = [];
  1664. foreach ($aBarrios as $barrio) {
  1665. $aCondBarrios[] = "doc['fk_id_tbl_barrios'].value != " . $barrio;
  1666. }
  1667.  
  1668. if (\count(\explode(',', $params['distritos'])) === 1) {
  1669. $aCondBarrios[] = "doc['fk_id_tbl_barrios'].value != 0";
  1670. }
  1671.  
  1672. $condBarrios = \implode(' && ', $aCondBarrios);
  1673. } else {
  1674. $condBarrios = "doc['fk_id_tbl_barrios'].value != 0";
  1675. }
  1676.  
  1677. $sorting = [
  1678. '_script' => [
  1679. 'script' => '((doc[\'foto\'].value == 0 || (' . $condDistritos . '))?70:'
  1680. . '((' . $condBarrios . ')?((doc[\'boosting_multirequest\'].value == 1)?5:50):0)) + '
  1681. . '((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == 1)?0:'
  1682. . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == 0)?10:'
  1683. . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 1)?20:'
  1684. . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == -1)?60:'
  1685. . ' ((doc[\'pago\'].value == 0 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 1)?30:'
  1686. . ' ((doc[\'pago\'].value == 0 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2)?40:50)'
  1687. . ' )'
  1688. . ' )'
  1689. . ' )'
  1690. . ' )'
  1691. . ')',
  1692. 'type' => 'number',
  1693. 'order' => 'asc', //,
  1694. ],
  1695. ];
  1696.  
  1697. return $sorting;
  1698. }
  1699.  
  1700. /**
  1701. * @param $searchParamOrderField
  1702. * @param $config
  1703. * @param $order
  1704. * @return array
  1705. */
  1706. protected function orderSearchByFields($searchParamOrderField, $searchParamTypeOrder, $config, $order): array
  1707. {
  1708. if (\is_array($searchParamOrderField)) {
  1709. $orderFieldList = \str_replace('alquiler ', '', $searchParamOrderField);
  1710. } else {
  1711. $orderFieldList = [];
  1712. $orderFieldList[] = \str_replace('alquiler ', '', $searchParamOrderField);
  1713. }
  1714.  
  1715. $searchParamTypeOrderList = $searchParamTypeOrder;
  1716. if (!\is_array($searchParamTypeOrder)) {
  1717. $searchParamTypeOrderList = [$searchParamTypeOrder];
  1718. }
  1719.  
  1720. while (\count($searchParamTypeOrderList) < \count($orderFieldList)) {
  1721. if (isset($this->search_params['type_order']) && $this->search_params['type_order']) {
  1722. $searchParamTypeOrderList[] = $config['order_type'] = \str_replace('alquiler ', '', $this->search_params['type_order']);
  1723. } else {
  1724. $searchParamTypeOrderList[] = null;
  1725. }
  1726. }
  1727.  
  1728. $orderList = \array_combine($orderFieldList, $searchParamTypeOrderList);
  1729.  
  1730. foreach ($orderList as $orderField => $orderType) {
  1731. $userOrder = ['order' => $orderField];
  1732. if (ENABLE_SEARCH_ORDER_BY_PREMIUM) {
  1733. $userOrder['order_type'] = $orderType;
  1734. $order[] = $userOrder;
  1735. } else {
  1736. $userOrder['order_type'] = $orderType;
  1737. // if order_field is "ordenación Enalquiler" or premium
  1738. if (\strcasecmp($searchParamOrderField, 'orden') === 0) {
  1739. // add the custom order after BOL availability order
  1740. $order[] = $userOrder;
  1741. } else {
  1742. // else, BOL availability order goes last.
  1743. \array_unshift($order, $userOrder);
  1744. }
  1745. }
  1746. }
  1747.  
  1748. return $order;
  1749. }
  1750.  
  1751. private function removeFilters($queryFilters, $_removeFilters)
  1752. {
  1753. foreach ($queryFilters as $key => $value) {
  1754. if (\in_array($value['field'], $_removeFilters)) {
  1755. unset($queryFilters[$key]);
  1756. }
  1757. }
  1758.  
  1759. return $queryFilters;
  1760. }
  1761.  
  1762. private function processResults($results, $config)
  1763. {
  1764. $locale = $this->getEnvironment()->getCurrentLanguage();
  1765. $aInfo = ['searchResults' => []];
  1766. $dataProvider = new DataProvider();
  1767. $resultsDataProvider = $dataProvider->getSearchResults($results);
  1768.  
  1769. if ($resultsDataProvider) {
  1770. $aInfo = ['searchResults' => $resultsDataProvider,
  1771. 'total' => $results->getTotalHits(),
  1772. ];
  1773.  
  1774. if (isset($config['conFoto'])) {
  1775. try {
  1776. $conFoto = $results->getAggregation('conFoto');
  1777. $aInfo['total_con_foto'] = $conFoto['doc_count'];
  1778. } catch (\Exception $e) {
  1779. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1780. }
  1781. }
  1782. }
  1783.  
  1784. if ($results) {
  1785. if (isset($config['districts'])) {
  1786. try {
  1787. $agg = $results->getAggregation('districts');
  1788. $aInfo['districts'] = $dataProvider->getDistrictCounts($agg);
  1789.  
  1790. if (isset($config['neighborhoods'])) {
  1791. $subagg = $results->getAggregation('neighborhoods');
  1792. $aInfo['districts'] = $dataProvider->addDistrictNeighborhoodCounts($aInfo['districts'], $subagg);
  1793. }
  1794. } catch (\Exception $e) {
  1795. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1796. }
  1797. }
  1798.  
  1799. if (isset($config['neighborhoods'])) {
  1800. try {
  1801. $agg = $results->getAggregation('neighborhoods');
  1802. $aInfo['neighborhoods'] = $dataProvider->getNeighborhoodCounts($agg);
  1803. } catch (\Exception $e) {
  1804. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1805. }
  1806. }
  1807.  
  1808. $locationsAggregationName = 'locations';
  1809.  
  1810. if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
  1811. $locationsAggregationName .= '_' . $locale;
  1812. }
  1813.  
  1814. if (isset($config[$locationsAggregationName])) {
  1815. try {
  1816. $agg = $results->getAggregation($locationsAggregationName);
  1817. $aInfo['locations'] = $dataProvider->getLocationCounts($agg);
  1818. } catch (\Exception $e) {
  1819. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1820. }
  1821. }
  1822.  
  1823. $provinceAggregationName = 'provinces';
  1824.  
  1825. if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
  1826. $provinceAggregationName .= '_' . $locale;
  1827. }
  1828.  
  1829. if (isset($config[$provinceAggregationName])) {
  1830. try {
  1831. $agg = $results->getAggregation($provinceAggregationName);
  1832. $aInfo['provinces'] = $dataProvider->getProvinceCounts($agg);
  1833. } catch (\Exception $e) {
  1834. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1835. }
  1836. }
  1837.  
  1838. if (isset($config['closeLocations'])) {
  1839. try {
  1840. $agg = $results->getAggregation('closeLocations');
  1841. $aInfo['closeLocations'] = $dataProvider->getCloseLocationsCounts($agg);
  1842.  
  1843. foreach ($aInfo['closeLocations'] as $key => $val) {
  1844. if (isset($aInfo['locations'][$key])) {
  1845. $aInfo['closeLocations'][$key]['total'] = $aInfo['locations'][$key]['total'];
  1846. }
  1847. }
  1848. } catch (\Exception $e) {
  1849. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1850. }
  1851. }
  1852.  
  1853. if (isset($config['geoGrid'])) {
  1854. try {
  1855. $agg = $results->getAggregation('geogrid');
  1856.  
  1857. $aInfo['geoGrid'] = $dataProvider->getGeoGridInfo($agg);
  1858. } catch (\Exception $e) {
  1859. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1860. }
  1861. }
  1862.  
  1863. if (isset($config['priceHistogram'])) {
  1864. try {
  1865. $agg = $results->getAggregation('priceHistogram');
  1866.  
  1867. $aInfo['priceHistogram'] = $dataProvider->getPriceHistogram($agg);
  1868. } catch (\Exception $e) {
  1869. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1870. }
  1871. }
  1872.  
  1873. if (isset($config['priceHistogramOverBoundary'])) {
  1874. try {
  1875. $agg = $results->getAggregation('priceHistogramOverBoundary');
  1876.  
  1877. $aInfo['priceHistogramOverBoundary'] = $dataProvider->getPriceHistogramOverBoundary($agg);
  1878. } catch (\Exception $e) {
  1879. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1880. }
  1881. }
  1882. }
  1883.  
  1884. return $aInfo;
  1885. }
  1886.  
  1887. private function processSuggests($results)
  1888. {
  1889. $aInfo = [];
  1890. $dataProvider = new DataProvider();
  1891.  
  1892. if (isset($results['suggestion_home'])) {
  1893. $aInfo['suggestions'] = $dataProvider->getSuggestHome($results);
  1894. }
  1895.  
  1896. return $aInfo;
  1897. }
  1898.  
  1899. private function processCounts($results, $config)
  1900. {
  1901. $locale = $this->getEnvironment()->getCurrentLanguage();
  1902. $aInfo = [];
  1903. $dataProvider = new DataProvider();
  1904.  
  1905. if ($results) {
  1906. if (isset($config['districts'])) {
  1907. try {
  1908. $agg = $results->getAggregation('districts');
  1909. if (isset($this->search_params['poblacion'])) {
  1910. $aInfo['districts'] = [$this->search_params['poblacion'] => $dataProvider->getSuggestDistrictsCounts($agg)];
  1911. } else {
  1912. $aInfo['districts'] = $dataProvider->getSuggestDistrictsCounts($agg);
  1913. }
  1914. } catch (\Exception $e) {
  1915. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1916. }
  1917. }
  1918.  
  1919. if (isset($config['neighborhoods'])) {
  1920. try {
  1921. $agg = $results->getAggregation('neighborhoods');
  1922. $home = (isset($config['home']) && $config['home']) ? true : false;
  1923. $aInfo['neighborhoods'] = $dataProvider->getSuggestNeighborhoodsCounts($agg, $home, $config['url']);
  1924. } catch (\Exception $e) {
  1925. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1926. }
  1927. }
  1928.  
  1929. $locationNameAggregationName = 'locations';
  1930.  
  1931. if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
  1932. $locationNameAggregationName .= '_' . $locale;
  1933. }
  1934.  
  1935. if (isset($config[$locationNameAggregationName])) {
  1936. try {
  1937. $agg = $results->getAggregation($locationNameAggregationName);
  1938. if (isset($this->search_params['provincia'])) {
  1939. $aInfo['locations'] = [$this->search_params['provincia'] => $dataProvider->getSuggestLocationsCounts($agg)];
  1940. } else {
  1941. $aInfo['locations'] = $dataProvider->getSuggestLocationsCounts($agg);
  1942. }
  1943. } catch (\Exception $e) {
  1944. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1945. }
  1946. }
  1947.  
  1948. $provinceNameAggregation = 'provinces';
  1949.  
  1950. if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
  1951. $provinceNameAggregation .= '_' . $locale;
  1952. }
  1953.  
  1954. if (isset($config[$provinceNameAggregation])) {
  1955. try {
  1956. $agg = $results->getAggregation($provinceNameAggregation);
  1957. $aInfo['provinces'] = $dataProvider->getSuggestProvincesCounts($agg);
  1958. } catch (\Exception $e) {
  1959. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1960. }
  1961. }
  1962. }
  1963.  
  1964. return $aInfo;
  1965. }
  1966.  
  1967. private function executeSearch(ElasticaQueryBuilder $queryBuilder)
  1968. {
  1969. $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
  1970.  
  1971. try {
  1972. if (isset($this->search_params['debug']) && $this->search_params['debug'] && ENV != 'PROD') {
  1973. die(\json_encode($queryBuilder->getQuery(), 128));
  1974. }
  1975. $results = $indexInstance->search($queryBuilder->getQuery());
  1976. } catch (\Exception $e) {
  1977. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1978.  
  1979. return false;
  1980. }
  1981.  
  1982. return $results;
  1983. }
  1984.  
  1985. private function executeSuggest(ElasticaQueryBuilder $queryBuilder)
  1986. {
  1987. /* @var $clientInstance \Elastica\Client */
  1988. $clientInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.clients.site');
  1989.  
  1990. try {
  1991. $response = $clientInstance->request('suggests/_suggest', Request::GET, $queryBuilder->getQuery());
  1992. $results = $response->getData();
  1993. } catch (\Exception $e) {
  1994. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  1995.  
  1996. return false;
  1997. }
  1998.  
  1999. return $results;
  2000. }
  2001.  
  2002. private function aggregationSearch($config)
  2003. {
  2004. $queryBuilder = new ElasticaQueryBuilder();
  2005.  
  2006. $queryBuilder = $this->addQueryAgregations($queryBuilder, $config);
  2007.  
  2008. return $this->executeSearch($queryBuilder);
  2009. }
  2010.  
  2011. private function filteredSearch($config)
  2012. {
  2013. /** @var ElasticaQueryBuilder $queryBuilder */
  2014. $queryBuilder = new ElasticaQueryBuilder();
  2015. $queryBuilder = $this->addQueryType($queryBuilder, $config);
  2016.  
  2017. if (isset($this->search_params['date_from']) && isset($this->search_params['date_to'])) {
  2018. $queryBuilder->filterMust($config['queryFilters']);
  2019. } else {
  2020. $queryBuilder->filterAnd($config['queryFilters']);
  2021. }
  2022.  
  2023. $queryBuilder->size($config['size']);
  2024.  
  2025. if (isset($config['fields'])) {
  2026. $queryBuilder->fields($config['fields']);
  2027. }
  2028.  
  2029. if (isset($config['offset'])) {
  2030. $queryBuilder->offset(($config['offset'] < 0) ? 0 : $config['offset']);
  2031. }
  2032.  
  2033. if (isset($config['order']) && \is_array($config['order'])) {
  2034. foreach ($config['order'] as $order_field) {
  2035. $type = (isset($order_field['order_type'])) ? $order_field['order_type'] : false;
  2036. $queryBuilder->sort($order_field['order'], $type);
  2037. }
  2038. } else {
  2039. if (isset($config['order']) && isset($config['order_type'])) {
  2040. $queryBuilder->sort($config['order'], $config['order_type']);
  2041. }
  2042. }
  2043.  
  2044. $queryBuilder = $this->addQueryAgregations($queryBuilder, $config);
  2045. $queryBuilder = $this->addQueryHighlights($queryBuilder, $config);
  2046.  
  2047. return $this->executeSearch($queryBuilder);
  2048. }
  2049.  
  2050. private function geoSearch($config)
  2051. {
  2052. $queryBuilder = new ElasticaQueryBuilder();
  2053.  
  2054. $queryBuilder = $this->addQueryType($queryBuilder, $config);
  2055.  
  2056. $order = $config['order'];
  2057. foreach ($order as $key => $val) {
  2058. if ($val == 'geo_location.location') {
  2059. $order[$key] = ['_geo_distance' => [$val => $config['lat_lon'], 'order' => 'asc', 'unit' => 'km']];
  2060. }
  2061. }
  2062.  
  2063. $queryBuilder->filterAnd($config['queryFilters']);
  2064. if (isset($config['radius'])) {
  2065. $queryBuilder->filterGeo($config['lat_lon'], $config['radius']);
  2066. } else {
  2067. $queryBuilder->filterGeo($config['lat_lon']);
  2068. }
  2069. $queryBuilder->size($config['size'])
  2070. ->sortGeo($order);
  2071.  
  2072. $queryBuilder = $this->addQueryAgregations($queryBuilder, $config);
  2073.  
  2074. $results = $this->executeSearch($queryBuilder);
  2075.  
  2076. return $results;
  2077. }
  2078.  
  2079. private function mapSearch($config)
  2080. {
  2081. $queryBuilder = new ElasticaQueryBuilder();
  2082. $queryBuilder = $this->addQueryType($queryBuilder, $config);
  2083. $queryBuilder->filterAnd($config['queryFilters']);
  2084. $filtersArray = $queryBuilder->getQuery();
  2085.  
  2086. $filtersArray['filter']['and'][] =
  2087. [
  2088. 'geo_bounding_box' => [
  2089. 'location' => [
  2090. 'top_left' => [
  2091. 'lat' => $this->search_params['bounds']['top_left']['lat'],
  2092. 'lon' => $this->search_params['bounds']['top_left']['lon'],
  2093. ],
  2094. 'bottom_right' => [
  2095. 'lat' => $this->search_params['bounds']['bottom_right']['lat'],
  2096. 'lon' => $this->search_params['bounds']['bottom_right']['lon'],
  2097. ],
  2098. ],
  2099. ],
  2100. ];
  2101.  
  2102. $query = [
  2103. 'query' => [
  2104. 'filtered' => $filtersArray,
  2105. ],
  2106. 'aggs' => [
  2107. 'geogrid' => [
  2108. 'geohash_grid' => [
  2109. 'field' => 'location',
  2110. 'precision' => (empty($this->search_params['precision'])) ? 6 : (int) $this->search_params['precision'],
  2111. ],
  2112. 'aggs' => [
  2113. 'cell' => [
  2114. 'geo_bounds' => [
  2115. 'field' => 'location',
  2116. ],
  2117. ],
  2118. ],
  2119. ],
  2120. ],
  2121. ];
  2122.  
  2123. $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
  2124. try {
  2125. if (isset($this->search_params['debug']) && $this->search_params['debug'] && ENV != 'PROD') {
  2126. // die('<pre> ' . json_encode($queryBuilder->getQuery(), 1) . '</pre><br>---------<br>');
  2127. die('<pre> ' . \json_encode($query, 1) . '</pre><br>---------<br>');
  2128. }
  2129. //$results = $indexInstance->search($queryBuilder->getQuery());
  2130. $results = $indexInstance->search($query, ['search_type' => 'count']);
  2131. } catch (\Exception $e) {
  2132. $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
  2133.  
  2134. return false;
  2135. }
  2136.  
  2137. return $results;
  2138. }
  2139.  
  2140. private function calculateAggregationQueryFilters($queryFilters)
  2141. {
  2142. $aggregationsQueryFilters = [];
  2143. foreach ($this->aggregations as $name => $value) {
  2144. $aggregationQueryFilters[$name] = $value['default'];
  2145. if (\count($queryFilters)) {
  2146. foreach ($queryFilters as $aggName => $queryFilter) {
  2147. if (isset($queryFilter['field']) && !\in_array($queryFilter['field'], $value['exclude'])) {
  2148. $aggregationQueryFilters[$name][] = $queryFilter;
  2149. }
  2150. }
  2151. }
  2152. }
  2153.  
  2154. return $aggregationQueryFilters;
  2155. }
  2156.  
  2157. private function addQueryAgregations($queryBuilder, $config)
  2158. {
  2159. foreach ($this->aggregations as $name => $value) {
  2160. if (isset($config[$name])) {
  2161. $agg_config = [
  2162. 'name' => $name,
  2163. 'type' => $config[$name]['type'],
  2164. 'aggs_type' => $config[$name]['aggs_type'],
  2165. 'filters' => $config[$name]['queryFilters'], ];
  2166.  
  2167. if (isset($config[$name]['order'])) {
  2168. $agg_config['order'] = $config[$name]['order'];
  2169. }
  2170. if (isset($config[$name]['order_type'])) {
  2171. $agg_config['order_type'] = $config[$name]['order_type'];
  2172. }
  2173. if (isset($config[$name]['script'])) {
  2174. $agg_config['script'] = $config[$name]['script'];
  2175. }
  2176. if (isset($config[$name]['field'])) {
  2177. $agg_config['field'] = $config[$name]['field'];
  2178. }
  2179. if (isset($config[$name]['size'])) {
  2180. $agg_config['size'] = $config[$name]['size'];
  2181. }
  2182. if (isset($config[$name]['interval'])) {
  2183. $agg_config['interval'] = $config[$name]['interval'];
  2184. }
  2185. if (isset($config[$name]['min_doc_count'])) {
  2186. $agg_config['min_doc_count'] = $config[$name]['min_doc_count'];
  2187. }
  2188. if (isset($config[$name]['min'])) {
  2189. $agg_config['min'] = $config[$name]['min'];
  2190. }
  2191. if (isset($config[$name]['max'])) {
  2192. $agg_config['max'] = $config[$name]['max'];
  2193. }
  2194.  
  2195. $queryBuilder->aggregation($agg_config);
  2196. }
  2197. }
  2198.  
  2199. return $queryBuilder;
  2200. }
  2201.  
  2202. private function addQueryHighlights($queryBuilder, $config)
  2203. {
  2204. if (isset($config['textQuery']) && $config['textQuery']) {
  2205. $queryBuilder->highlight($this->highlight);
  2206. }
  2207.  
  2208. return $queryBuilder;
  2209. }
  2210.  
  2211. private static function replaceQuery(&$item, &$value, $query): void
  2212. {
  2213. $item = \str_replace('*', $query, $item);
  2214. }
  2215.  
  2216. private static function replaceMinShouldMatch(&$item, &$value, $minShouldMatch): void
  2217. {
  2218. $item = \str_replace('?', $minShouldMatch, $item);
  2219. }
  2220.  
  2221. private function addQueryType($queryBuilder, $config)
  2222. {
  2223. if (isset($config['textQuery']) && $config['textQuery']) {
  2224. $queryType = $this->getQueryType();
  2225. \array_walk_recursive($queryType, 'self::replaceQuery', $this->processQueryString($config['textQuery']));
  2226. $this->setQueryType($queryType);
  2227. $queryBuilder->query($queryType);
  2228. }
  2229.  
  2230. if (isset($config['minShouldMatch']) && $config['minShouldMatch']) {
  2231. $queryType = $this->getQueryType();
  2232. \array_walk_recursive($queryType, 'self::replaceMinShouldMatch', $config['minShouldMatch']);
  2233. $this->setQueryType($queryType);
  2234. $queryBuilder->query($queryType);
  2235. }
  2236.  
  2237. return $queryBuilder;
  2238. }
  2239.  
  2240. private function setQueryAggregations($queryFilters, $config, $exclude = [])
  2241. {
  2242. $aggregationsQueryFilters = $this->calculateAggregationQueryFilters($queryFilters);
  2243.  
  2244. foreach ($this->aggregations as $key => $value) {
  2245. if (!\in_array($key, $exclude)) {
  2246. $config[$key] = ['name' => $key];
  2247. if (isset($value['script'])) {
  2248. $config[$key]['script'] = $value['script'];
  2249. }
  2250. if (isset($value['field'])) {
  2251. $config[$key]['field'] = $value['field'];
  2252. }
  2253. if (isset($aggregationsQueryFilters[$key])) {
  2254. $config[$key]['queryFilters'] = $aggregationsQueryFilters[$key];
  2255. }
  2256. if (isset($value['order'])) {
  2257. $config[$key]['order'] = $value['order'];
  2258. }
  2259. if (isset($value['aggs_type'])) {
  2260. $config[$key]['aggs_type'] = $value['aggs_type'];
  2261. }
  2262. if (isset($value['order_type'])) {
  2263. $config[$key]['order_type'] = $value['order_type'];
  2264. }
  2265. if (isset($value['type'])) {
  2266. $config[$key]['type'] = $value['type'];
  2267. }
  2268. if (isset($value['size'])) {
  2269. $config[$key]['size'] = $value['size'];
  2270. }
  2271. if (isset($value['interval'])) {
  2272. $config[$key]['interval'] = $value['interval'];
  2273. }
  2274. if (isset($value['min_doc_count'])) {
  2275. $config[$key]['min_doc_count'] = $value['min_doc_count'];
  2276. }
  2277. if (isset($value['min'])) {
  2278. $config[$key]['min'] = $value['min'];
  2279. }
  2280. if (isset($value['max'])) {
  2281. $config[$key]['max'] = $value['max'];
  2282. }
  2283. }
  2284. }
  2285.  
  2286. return $config;
  2287. }
  2288.  
  2289. private function getLocationCoords()
  2290. {
  2291. $em = \Enalquiler\Core\DI\DIContainer::getInstance()->get('doctrine')->getManager('read');
  2292.  
  2293. //TODO: Change to use doctrine entity
  2294. $sql = 'SELECT longitud, latitud FROM tbl_poblaciones WHERE id = ' . $this->search_params['poblacion'];
  2295.  
  2296. return \current($em->getConnection()->fetchAll($sql));
  2297. }
  2298.  
  2299. private function getLocationShowLevels()
  2300. {
  2301. $em = \Enalquiler\Core\DI\DIContainer::getInstance()->get('doctrine')->getManager('read');
  2302.  
  2303. //TODO: Change to use doctrine entity
  2304. $sql = 'SELECT mostrar_niveles FROM tbl_poblaciones WHERE id = ' . $this->search_params['poblacion'];
  2305. $result = \current($em->getConnection()->fetchAll($sql));
  2306.  
  2307. return $result['mostrar_niveles'];
  2308. }
  2309.  
  2310. private function getDistrictCoords()
  2311. {
  2312. $em = \Enalquiler\Core\DI\DIContainer::getInstance()->get('doctrine')->getManager('read');
  2313.  
  2314. //TODO: Change to use doctrine entity
  2315. $sql = 'SELECT longitud, latitud FROM tbl_distritos WHERE id = ' . $this->search_params['distritos'];
  2316.  
  2317. return \current($em->getConnection()->fetchAll($sql));
  2318. }
  2319.  
  2320. private function getNeighborhoodCoords()
  2321. {
  2322. $em = \Enalquiler\Core\DI\DIContainer::getInstance()->get('doctrine')->getManager('read');
  2323.  
  2324. //TODO: Change to use doctrine entity
  2325. $sql = 'SELECT longitud, latitud FROM tbl_barrios WHERE id = ' . $this->search_params['barrio'];
  2326.  
  2327. return \current($em->getConnection()->fetchAll($sql));
  2328. }
  2329.  
  2330. private function getQueryFiltersToSearch($params)
  2331. {
  2332. $queryFilters = [];
  2333. $this->setFilterCocinaEquipada($queryFilters, $params);
  2334. $this->setFilterAntiguedad($queryFilters, $params);
  2335. $this->setFilterObranueva($queryFilters, $params);
  2336. $this->setFilterTipoUsuario($queryFilters, $params);
  2337. $this->setFiltersLocation($queryFilters, $params);
  2338. $this->setFiltersPrecio($queryFilters, $params);
  2339. $this->setFilterMetros2($queryFilters, $params);
  2340. $this->setFilterHabitaciones($queryFilters, $params);
  2341. $this->setFilterBanos($queryFilters, $params);
  2342. $this->setFilterCocina($queryFilters, $params);
  2343. $this->setFilterJardin($queryFilters, $params);
  2344. $this->setFilterFecha($queryFilters, $params);
  2345. $this->setFilterFechaPublicacion($queryFilters, $params);
  2346. $this->setFilterFechaUltimoCambioPrecio($queryFilters, $params);
  2347. $this->setFilterAmueblado($queryFilters, $params);
  2348. $this->setFilterOpcionCompra($queryFilters, $params);
  2349. $this->setFilterGaraje($queryFilters, $params);
  2350. $this->setFilterExterior($queryFilters, $params);
  2351. $this->setFilterAscensor($queryFilters, $params);
  2352. $this->setFilterAnimales($queryFilters, $params);
  2353. $this->setFilterAireAcondicionado($queryFilters, $params);
  2354. $this->setFilterPiscina($queryFilters, $params);
  2355. $this->setFilterTerraza($queryFilters, $params);
  2356. $this->setFilterCalefaccion($queryFilters, $params);
  2357. $this->setFilterMinusvalidos($queryFilters, $params);
  2358. $this->setFilterFoto($queryFilters, $params);
  2359. $this->setFilterMicrosite($queryFilters, $params);
  2360. $this->setFilterExcludeIds($queryFilters, $params);
  2361. $this->setFilterIds($queryFilters, $params);
  2362. $this->setFilterIntegracion($queryFilters, $params);
  2363. $this->setFilterSameUser($queryFilters, $params);
  2364. $this->setFilterProvinceCapital($queryFilters, $params);
  2365. $this->setFilterEsconderMapa($queryFilters, $params);
  2366. $this->setFilterPago($queryFilters, $params);
  2367. $this->setFilterMaxLevel($queryFilters, $params);
  2368. $this->setFilterBajadaPrecio($queryFilters, $params);
  2369. $this->setFilterOnlineBooking($queryFilters, $params);
  2370. $this->setFilterBookingOnlineNextMonthsAvailable($queryFilters, $params);
  2371. $this->setFilterGeohash($queryFilters, $params);
  2372. $this->setFilterGeolocationPoints($queryFilters, $params);
  2373. $this->setFilterGeoLocationRadius($queryFilters, $params);
  2374. $this->setFilterAvailabilityDates($queryFilters, $params);
  2375. $this->setAvailabilityMinimumDays($queryFilters, $params);
  2376. $this->setFilterAccesoMinusvalidos($queryFilters, $params);
  2377. $this->setFilterHasPositioning($queryFilters, $params);
  2378. $this->setFilterFullProperty($queryFilters, $params);
  2379.  
  2380. // Filters that only apply to FLATS category (piso, atico, loft, ... all but habitaciones)
  2381. $flatQueryFilter[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 0];
  2382. $this->setFilterPeopleCapacity($flatQueryFilter, $params);
  2383. $this->setFilterTipoVivienda($flatQueryFilter, $params);
  2384. $flatOnlyQueryFiltersAnd[] = ['type' => 'and', 'field' => 'and_properties', 'value' => $flatQueryFilter];
  2385.  
  2386. // Filters that only apply to ROOMS category (habitacion)
  2387. $roomsQueryFilters[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 1];
  2388. $this->setFilterSmoker($roomsQueryFilters, $params);
  2389. $this->setFilterRoomerGenderPreference($roomsQueryFilters, $params);
  2390. $this->setFilterBedSize($roomsQueryFilters, $params);
  2391. $this->setFilterRoomSize($roomsQueryFilters, $params);
  2392. $this->setFilterPrivateBathroom($roomsQueryFilters, $params);
  2393. $this->setFilterDoorLock($roomsQueryFilters, $params);
  2394. $roomsOnlyQueryFiltersAnd[] = ['type' => 'and', 'field' => 'and_rooms', 'value' => $roomsQueryFilters];
  2395.  
  2396. if (isset($params['online_booking']) && $params['online_booking'] == 1) {
  2397. $queryFilters[] = [
  2398. 'type' => 'or',
  2399. 'field' => 'or_tipos',
  2400. 'value' => \array_merge($roomsOnlyQueryFiltersAnd, $flatOnlyQueryFiltersAnd)
  2401. ];
  2402. } else {
  2403. $queryFilters = \array_merge($queryFilters, $flatQueryFilter);
  2404. }
  2405.  
  2406. return $queryFilters;
  2407. }
  2408.  
  2409. private function setFilterSameUser(&$queryFilters, $params): void
  2410. {
  2411. if (isset($params['user'])) {
  2412. if (!\is_array($params['user'])) {
  2413. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_usuarios', 'value' => $params['user']];
  2414. } else {
  2415. $aUsers = [];
  2416. foreach ($params['user'] as $user) {
  2417. $aUsers[] = ['type' => 'term', 'field' => 'fk_id_tbl_usuarios', 'value' => $user];
  2418. }
  2419. $queryFilters[] = ['type' => 'or', 'field' => 'or_usuarios', 'value' => $aUsers];
  2420. }
  2421. }
  2422. }
  2423.  
  2424. private function setFilterCocinaEquipada(&$queryFilters, $params): void
  2425. {
  2426. if (isset($params['cocina_equipada']) && $params['cocina_equipada']) {
  2427. $queryFilters[] = ['type' => 'term', 'field' => 'cocina_equipada', 'value' => 1];
  2428. }
  2429. }
  2430.  
  2431. private function setFilterAntiguedad(&$queryFilters, $params): void
  2432. {
  2433. if (isset($params['antiguedad']) && $params['antiguedad']) {
  2434. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_antiguedad_inmuebles', 'value' => (int) $params['antiguedad']];
  2435. }
  2436. }
  2437.  
  2438. private function setFilterObranueva(&$queryFilters, $params): void
  2439. {
  2440. if (isset($params['obra_nueva']) && $params['obra_nueva']) {
  2441. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_estado_inmuebles', 'value' => 3];
  2442. }
  2443. }
  2444.  
  2445. private function setFilterTipoUsuario(&$queryFilters, $params): void
  2446. {
  2447. // hack para landings particular => forzamos el filtro por tipo
  2448. if (isset($params['desde_footer']) && $params['desde_footer'] == 1 && isset($params['query_string']) && \strstr(
  2449. $params['query_string'],
  2450. 'particular'
  2451. )) {
  2452. $params['tipo_usuario'] = 1;
  2453. }
  2454.  
  2455. if (isset($params['tipo_usuario']) && $params['tipo_usuario']) {
  2456. $tipo = ($params['tipo_usuario'] == 3) ? 2 : $params['tipo_usuario'];
  2457. $queryFilters[] = ['type' => 'range', 'field' => 'dn_fk_id_tbl_tipo_usuarios', 'value' => ['gte' => $tipo,
  2458. 'lte' => $tipo, ]];
  2459. if ($params['tipo_usuario'] == 3) {
  2460. $queryFilters[] = ['type' => 'term', 'field' => 'pago', 'value' => 1];
  2461. }
  2462. }
  2463. }
  2464.  
  2465. private function setFiltersLocation(&$queryFilters, $params): void
  2466. {
  2467. if (isset($params['provincia']) && $params['provincia']) {
  2468. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_provincias', 'value' => $params['provincia']];
  2469. }
  2470.  
  2471. if (isset($params['poblacion']) && $params['poblacion']) {
  2472. if (isset($params['pobprox']) && $params['pobprox']) {
  2473. $i = 0;
  2474. $aPoblaciones[$i] = $params['poblacion'];
  2475. $aPobs = [
  2476. ['type' => 'term', 'field' => 'fk_id_tbl_poblaciones', 'value' => $params['poblacion']],
  2477. ];
  2478.  
  2479. foreach ($params['pobprox'] as $pprox) {
  2480. ++$i;
  2481. $aPoblaciones[$i] = $pprox;
  2482. $aPobs[] = ['type' => 'term', 'field' => 'fk_id_tbl_poblaciones', 'value' => $pprox];
  2483. }
  2484.  
  2485. $queryFilters[] = ['type' => 'or', 'field' => 'or_poblaciones', 'value' => $aPobs];
  2486. } else {
  2487. if (!\is_array($params['poblacion'])) {
  2488. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_poblaciones', 'value' => $params['poblacion']];
  2489. } else {
  2490. $aPobs = [];
  2491. $i = 0;
  2492. foreach ($params['poblacion'] as $pob) {
  2493. $aPoblaciones[$i] = $pob;
  2494. $aPobs[] = ['type' => 'term', 'field' => 'fk_id_tbl_poblaciones', 'value' => $pob];
  2495. ++$i;
  2496. }
  2497. $queryFilters[] = ['type' => 'or', 'field' => 'or_poblaciones', 'value' => $aPobs];
  2498. }
  2499. }
  2500. }
  2501.  
  2502. $this->setFilterBarriosDistritos($queryFilters, $params);
  2503. }
  2504.  
  2505. private function setFilterTipoVivienda(&$queryFilters, $params): void
  2506. {
  2507. //tipo de vivienda
  2508. if (isset($params['tipo']) && $params['tipo'] && $params['tipo'] != 1) {
  2509. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_categorias', 'value' => (int) $params['tipo']];
  2510. }
  2511. }
  2512.  
  2513. private function setFilterCocina(&$queryFilters, $params): void
  2514. {
  2515. //tipo de cocina
  2516. if (isset($params['cocina']) && $params['cocina'] && $params['cocina'] != 1) {
  2517. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_cocina', 'value' => (int) $params['cocina']];
  2518. }
  2519. }
  2520.  
  2521. private function setFiltersPrecio(&$queryFilters, $params): void
  2522. {
  2523. if (!empty($params['precio_min']) && !empty($params['precio_max'])) {
  2524. $queryFilters[] = ['type' => 'range', 'field' => $this->getFieldPrice($params), 'value' => ['gte' => $params['precio_min'],
  2525. 'lte' => $params['precio_max'], ]];
  2526. } elseif (!empty($params['precio_max'])) {
  2527. $queryFilters[] = ['type' => 'range', 'field' => $this->getFieldPrice($params), 'value' => ['lte' => $params['precio_max']]];
  2528. } elseif (!empty($params['precio_min'])) {
  2529. $queryFilters[] = ['type' => 'range', 'field' => $this->getFieldPrice($params), 'value' => ['gte' => $params['precio_min']]];
  2530. }
  2531. }
  2532.  
  2533. private function setFilterMetros2(&$queryFilters, $params): void
  2534. {
  2535. if (isset($params['metros2']) && $params['metros2']) {
  2536. $queryFilters[] = ['type' => 'range', 'field' => 'metros2', 'value' => ['gte' => $params['metros2']]];
  2537. }
  2538.  
  2539. if (!empty($params['metros_min'])) {
  2540. $queryFilters[] = ['type' => 'range', 'field' => 'metros2', 'value' => ['gte' => $params['metros_min']]];
  2541. }
  2542.  
  2543. if (!empty($params['metros_max'])) {
  2544. $queryFilters[] = ['type' => 'range', 'field' => 'metros2', 'value' => ['lte' => $params['metros_max']]];
  2545. }
  2546. }
  2547.  
  2548. private function setFilterHabitaciones(&$queryFilters, $params): void
  2549. {
  2550. if (!empty($params['habitaciones'])) {
  2551. $queryFilters[] = ['type' => 'range', 'field' => 'num_habitaciones', 'value' => ['gte' => $params['habitaciones']]];
  2552. }
  2553.  
  2554. if (!empty($params['habitaciones_min'])) {
  2555. $queryFilters[] = ['type' => 'range', 'field' => 'num_habitaciones', 'value' => ['gte' => $params['habitaciones_min']]];
  2556. }
  2557.  
  2558. if (!empty($params['habitaciones_max'])) {
  2559. $queryFilters[] = ['type' => 'range', 'field' => 'num_habitaciones', 'value' => ['lte' => $params['habitaciones_max']]];
  2560. }
  2561. }
  2562.  
  2563. private function setFilterBanos(&$queryFilters, $params): void
  2564. {
  2565. if (isset($params['banos']) && $params['banos']) {
  2566. $queryFilters[] = ['type' => 'range', 'field' => 'num_banos', 'value' => ['gte' => $params['banos']]];
  2567. }
  2568. }
  2569.  
  2570. private function setFilterJardin(&$queryFilters, $params): void
  2571. {
  2572. if (isset($params['jardin']) && $params['jardin']) {
  2573. $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_jardin', 'value' => ['gt' => 1]];
  2574. }
  2575. }
  2576.  
  2577. private function setFilterFecha(&$queryFilters, $params): void
  2578. {
  2579. if (isset($params['fecha']) && $params['fecha']) {
  2580. $date = new \DateTime();
  2581.  
  2582. switch ($params['fecha']) {
  2583. case 1: // Last 24h
  2584. $date->sub(new \DateInterval('PT24H'));
  2585. $fecha = $date->getTimestamp();
  2586. break;
  2587.  
  2588. case 2: // Last 72h
  2589. $date->sub(new \DateInterval('PT72H'));
  2590. $fecha = $date->getTimestamp();
  2591. break;
  2592.  
  2593. case 3: //This week
  2594. $date->sub(new \DateInterval('P7D'));
  2595. $fecha = $date->getTimestamp();
  2596. break;
  2597.  
  2598. case 4: //This month
  2599. $date->sub(new \DateInterval('P30D'));
  2600. $fecha = $date->getTimestamp();
  2601. break;
  2602.  
  2603. default:
  2604. $fecha = '';
  2605. }
  2606.  
  2607. if ($fecha) {
  2608. $queryFilters[] = ['type' => 'range', 'field' => 'fec_alta', 'value' => ['gte' => $fecha]];
  2609. }
  2610. }
  2611. }
  2612.  
  2613. private function setFilterFechaPublicacion(&$queryFilters, $params): void
  2614. {
  2615. if (isset($params['fec_publicacion']) && $params['fec_publicacion']) {
  2616. $queryFilters[] = ['type' => 'range', 'field' => 'fec_publicacion', 'value' => ['gte' => $params['fec_publicacion']]];
  2617. }
  2618. }
  2619.  
  2620. private function setFilterFechaUltimoCambioPrecio(&$queryFilters, $params): void
  2621. {
  2622. if (isset($params['fec_ultimo_cambio_precio']) && $params['fec_ultimo_cambio_precio']) {
  2623. $queryFilters[] = ['type' => 'range', 'field' => 'fec_ultimo_cambio_precio', 'value' => ['gte' => $params['fec_ultimo_cambio_precio']]];
  2624. }
  2625. }
  2626.  
  2627. private function setFilterAmueblado(&$queryFilters, $params): void
  2628. {
  2629. //online_booking check
  2630. if (isset($params['online_booking']) && $params['online_booking'] == 1) {
  2631. $params['amueblado'] = 1;
  2632. }
  2633. // hack para landings amueblado => forzamos el filtro por tipo
  2634. if (isset($params['desde_footer']) && $params['desde_footer'] == 1 && isset($params['query_string']) && \strstr(
  2635. $params['query_string'],
  2636. 'amueblado'
  2637. )) {
  2638. $params['amueblado'] = 1;
  2639. }
  2640.  
  2641. if (isset($params['amueblado'])) {
  2642. if (2 == $params['amueblado']) {
  2643. $queryFilters[] = ['type' => 'term', 'field' => 'amueblado', 'value' => 0];
  2644. } else {
  2645. $queryFilters[] = ['type' => 'range', 'field' => 'amueblado', 'value' => ['gte' => 1]];
  2646. }
  2647. }
  2648. }
  2649.  
  2650. private function setFilterOpcionCompra(&$queryFilters, $params): void
  2651. {
  2652. if (isset($params['opcion_compra']) && $params['opcion_compra']) {
  2653. $queryFilters[] = ['type' => 'term', 'field' => 'opcion_compra', 'value' => (int) $params['opcion_compra']];
  2654. }
  2655. }
  2656.  
  2657. private function setFilterGaraje(&$queryFilters, $params): void
  2658. {
  2659. if (isset($params['garaje_incluido']) && $params['garaje_incluido']) {
  2660. $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_parking', 'value' => ['gte' => 2, 'lte' => 3]];
  2661. }
  2662. }
  2663.  
  2664. private function setFilterExterior(&$queryFilters, $params): void
  2665. {
  2666. if (isset($params['exterior']) && $params['exterior']) {
  2667. $queryFilters[] = ['type' => 'term', 'field' => 'exterior', 'value' => (int) $params['exterior']];
  2668. }
  2669. }
  2670.  
  2671. private function setFilterAscensor(&$queryFilters, $params): void
  2672. {
  2673. if (isset($params['ascensor']) && $params['ascensor']) {
  2674. $queryFilters[] = ['type' => 'term', 'field' => 'ascensor', 'value' => (int) $params['ascensor']];
  2675. }
  2676. }
  2677.  
  2678. private function setFilterAnimales(&$queryFilters, $params): void
  2679. {
  2680. if (isset($params['acepta_animales']) && $params['acepta_animales']) {
  2681. $queryFilters[] = ['type' => 'term', 'field' => 'acepta_animales', 'value' => (int) $params['acepta_animales']];
  2682. }
  2683. }
  2684.  
  2685. private function setFilterAireAcondicionado(&$queryFilters, $params): void
  2686. {
  2687. if (isset($params['aa']) && $params['aa']) {
  2688. $queryFilters[] = ['type' => 'term', 'field' => 'aa', 'value' => (int) $params['aa']];
  2689. }
  2690. }
  2691.  
  2692. private function setFilterPiscina(&$queryFilters, $params): void
  2693. {
  2694. if (isset($params['piscina']) && $params['piscina']) {
  2695. $queryFilters[] = ['type' => 'term', 'field' => 'piscina', 'value' => (int) $params['piscina']];
  2696. }
  2697. }
  2698.  
  2699. private function setFilterTerraza(&$queryFilters, $params): void
  2700. {
  2701. if (isset($params['terraza']) && $params['terraza']) {
  2702. $queryFilters[] = ['type' => 'term', 'field' => 'terraza', 'value' => (int) $params['terraza']];
  2703. }
  2704. }
  2705.  
  2706. private function setFilterCalefaccion(&$queryFilters, $params): void
  2707. {
  2708. if (isset($params['calefaccion']) && $params['calefaccion']) {
  2709. $queryFilters[] = ['type' => 'term', 'field' => 'calefaccion', 'value' => (int) $params['calefaccion']];
  2710. }
  2711. }
  2712.  
  2713. private function setFilterMinusvalidos(&$queryFilters, $params): void
  2714. {
  2715. if (isset($params['minusvalidos']) && $params['minusvalidos']) {
  2716. $queryFilters[] = ['type' => 'term', 'field' => 'minusvalidos', 'value' => (int) $params['minusvalidos']];
  2717. }
  2718. }
  2719.  
  2720. private function setFilterFoto(&$queryFilters, $params): void
  2721. {
  2722. if (isset($params['con_foto']) && $params['con_foto']) {
  2723. $queryFilters[] = ['type' => 'range', 'field' => 'foto', 'value' => ['gte' => 1]];
  2724. }
  2725. }
  2726.  
  2727. private function setFilterEsconderMapa(&$queryFilters, $params): void
  2728. {
  2729. if (isset($params['esconder_mapa']) && $params['esconder_mapa']) {
  2730. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_esconder_en_mapa', 'value' => (int) $params['esconder_mapa']];
  2731. }
  2732. }
  2733.  
  2734. private function setFilterPago(&$queryFilters, $params): void
  2735. {
  2736. if (isset($params['pago']) && $params['pago']) {
  2737. $queryFilters[] = ['type' => 'term', 'field' => 'pago', 'value' => (int) $params['pago']];
  2738. }
  2739. }
  2740.  
  2741. private function setFilterBajadaPrecio(&$queryFilters, $params): void
  2742. {
  2743. if (isset($params['bajada_precio']) && ($params['bajada_precio'] == 1)) {
  2744. $queryFilters[] = ['type' => 'range', 'field' => 'bajada_precio', 'value' => ['gt' => 0]];
  2745. }
  2746. }
  2747.  
  2748. private function setFilterOnlineBooking(&$queryFilters, $params): void
  2749. {
  2750. /** @var BookingOnline $bookingOnlineService */
  2751. $bookingOnlineService = Service::factory(Service::SRV_BOOKINGONLINE);
  2752. if ($bookingOnlineService->isServiceEnabled() === false) {
  2753. $queryFilters[] = ['type' => 'term', 'field' => 'booking_online', 'value' => 0];
  2754. } else {
  2755. if (isset($params['online_booking']) && $params['online_booking']) {
  2756. $queryFilters[] = ['type' => 'term', 'field' => 'booking_online', 'value' => 1];
  2757.  
  2758. $order = [
  2759. ['order' => 'bookingOnlineNextMonthsAvailable', 'order_type' => 'desc'],
  2760. ['order' => 'orden', 'order_type' => 'asc'],
  2761. ['order' => 'precio_por_metros2', 'order_type' => 'asc'],
  2762. ];
  2763.  
  2764. $this->addSearchParam(['order_booking_online' => $order]);
  2765. } elseif (isset($params['online_booking']) && !$params['online_booking']) {
  2766. $queryFilters[] = ['type' => 'term', 'field' => 'booking_online', 'value' => 0];
  2767. }
  2768. }
  2769. }
  2770.  
  2771. private function setFilterBookingOnlineNextMonthsAvailable(&$queryFilters, $params): void
  2772. {
  2773. if (isset($params['bookingOnlineNextMonthsAvailable'])) {
  2774. $queryFilters[] = [
  2775. 'type' => 'term',
  2776. 'field' => 'bookingOnlineNextMonthsAvailable',
  2777. 'value' => $params['bookingOnlineNextMonthsAvailable'],
  2778. ];
  2779. }
  2780. }
  2781.  
  2782. private function setFilterGeohash(&$queryFilters, $params): void
  2783. {
  2784. if (isset($params['geohash'])) {
  2785. $queryFilters[] = [
  2786. 'type' => 'geohash_cell',
  2787. 'field' => [
  2788. 'location' => [
  2789. 'geohash' => \strtolower($params['geohash']),
  2790. ],
  2791. 'precision' => \strlen($params['geohash']),
  2792. ],
  2793. ];
  2794. }
  2795. }
  2796.  
  2797. private function setFilterGeolocationPoints(&$queryFilters, $params): void
  2798. {
  2799. if (isset($params['geolocation_points'])) {
  2800. $queryFilters[] = [
  2801. 'type' => 'geo_polygon',
  2802. 'field' => [
  2803. 'location' => [
  2804. 'points' => $params['geolocation_points'],
  2805. ],
  2806. ],
  2807. ];
  2808. }
  2809. }
  2810.  
  2811. private function setFilterGeoLocationRadius(&$queryFilters, $params): void
  2812. {
  2813. if (isset($params['radius'], $params['lat_lon'])) {
  2814. $queryFilters[] = [
  2815. 'type' => 'geo_distance',
  2816. 'field' => [
  2817. 'location' => $params['lat_lon'],
  2818. 'distance' => $params['radius'] . 'km',
  2819. ],
  2820. ];
  2821. }
  2822. }
  2823.  
  2824. private function setFiltersGeo(&$queryFilters, $params): void
  2825. {
  2826. if (isset($params['lat_lon'])) {
  2827. $queryFilters[] = [
  2828. 'type' => 'geo',
  2829. 'field' => 'lat_lon',
  2830. 'value' => $params['lat_lon'],
  2831. ];
  2832. }
  2833.  
  2834. if (isset($params['radius'])) {
  2835. $queryFilters[] = [
  2836. 'type' => 'geo',
  2837. 'field' => 'radius',
  2838. 'value' => $params['radius'],
  2839. ];
  2840. }
  2841.  
  2842. if (isset($params['bounds'])) {
  2843. $queryFilters[] = [
  2844. 'type' => 'geo',
  2845. 'field' => 'bounds',
  2846. 'value' => $params['bounds'],
  2847. ];
  2848. }
  2849. }
  2850.  
  2851. private function setFilterMaxLevel(&$queryFilters, $params): void
  2852. {
  2853. if (isset($params['min_level']) && ($params['min_level'] == 0 || $params['min_level'] == -1 || $params['min_level'] == -2)) {
  2854. $queryFilters[] = ['type' => 'range', 'field' => 'second_level', 'value' => ['gte' => $params['min_level']]];
  2855. }
  2856. }
  2857.  
  2858. private function setFilterBarriosDistritos(&$queryFilters, $params): void
  2859. {
  2860. // si hay más de 1 distrito
  2861. if (isset($params['distritos']) && \count($params['distritos']) > 0 && !(isset($params['barrio_mapa']) && $params['barrio_mapa'])) {
  2862. if (!\is_array($params['distritos'])) {
  2863. if (\strpos($params['distritos'], '_')) {
  2864. $params['distritos'] = \explode('_', $params['distritos']);
  2865. } elseif (\strpos($params['distritos'], ',')) {
  2866. $params['distritos'] = \explode(',', $params['distritos']);
  2867. } elseif (\strpos($params['distritos'], '%2C')) {
  2868. $params['distritos'] = \explode('%2C', $params['distritos']);
  2869. $this->logger->debug('Urlencoded comma in ' . $this->search_params['searchType']);
  2870. } elseif ($params['distritos']) {
  2871. $params['distritos'] = [$params['distritos']];
  2872. }
  2873. }
  2874.  
  2875. if ($params['distritos']) {
  2876. $districtFilters = [];
  2877. foreach ($params['distritos'] as $district) {
  2878. $districtFilters[] = [
  2879. 'type' => 'term', 'field' => 'fk_id_tbl_distritos', 'value' => $district,
  2880. ];
  2881. }
  2882. $queryFilters[] = ['type' => 'or', 'field' => 'or_distritos', 'value' => $districtFilters];
  2883. }
  2884. }
  2885.  
  2886. // si hay solo 1 distrito, buscamos en sus barrios
  2887. if (isset($params['distritos']) && \count($params['distritos']) > 0 && !(isset($params['distrito_mapa']) && $params['distrito_mapa'])) {
  2888. //barrio
  2889. if (isset($params['barrios']) && \count($params['barrios']) > 0) {
  2890. if (!\is_array($params['barrios'])) {
  2891. if (\strpos($params['barrios'], '_')) {
  2892. $params['barrios'] = \explode('_', $params['barrios']);
  2893. } elseif (\strpos($params['barrios'], ',')) {
  2894. $params['barrios'] = \explode(',', $params['barrios']);
  2895. } elseif ($params['barrios']) {
  2896. $params['barrios'] = [$params['barrios']];
  2897. }
  2898. }
  2899. if ($params['barrios']) {
  2900. $neighborhoodFilters = [];
  2901. foreach ($params['barrios'] as $neighborhood) {
  2902. $neighborhoodFilters[] = [
  2903. 'type' => 'term', 'field' => 'fk_id_tbl_barrios', 'value' => $neighborhood,
  2904. ];
  2905. }
  2906. $queryFilters[] = ['type' => 'or', 'field' => 'or_barrios', 'value' => $neighborhoodFilters];
  2907. }
  2908. }
  2909. }
  2910. }
  2911.  
  2912. private function setFilterMicrosite(&$queryFilters, $params): void
  2913. {
  2914. // microsite GRAN CUENTA
  2915. if (isset($params['midgc']) && $params['midgc']) {
  2916. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_campanas_tbl_pack_grandes_cuentas', 'value' => $params['midgc']];
  2917. } elseif (isset($params['mid']) && $params['mid']) {
  2918. /* @var $serviceMicrosite Enalquiler\Modules\Product\Service\Microsite */
  2919. $serviceMicrosite = \Enalquiler\Core\DI\DIContainer::getInstance()->get('service.microsite');
  2920. $microsite = $serviceMicrosite->getMicrositeById($params['mid']);
  2921. if ($microsite) {
  2922. $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_usuarios', 'value' => $microsite->getUser()->getId()];
  2923. }
  2924. }
  2925. }
  2926.  
  2927. private function setFilterExcludeIds(&$queryFilters, $params): void
  2928. {
  2929. if (isset($params['excludeIds']) && \count($params['excludeIds'])) {
  2930. $queryFilters[] = ['type' => 'not', 'field' => 'ids', 'value' => ['values' => \array_values($params['excludeIds'])]];
  2931. }
  2932. }
  2933.  
  2934. private function setFilterIds(&$queryFilters, $params): void
  2935. {
  2936. if (isset($params['ids']) && \count($params['ids'])) {
  2937. $queryFilters[] = ['type' => 'ids', 'field' => 'values', 'value' => \array_values($params['ids'])];
  2938. }
  2939. }
  2940.  
  2941. private function setFilterIntegracion(&$queryFilters, $params): void
  2942. {
  2943. if (isset($params['fk_pid_tbl_usuarios']) && $params['fk_pid_tbl_usuarios'] !== false) {
  2944. $queryFilters[] = ['type' => 'range', 'field' => 'fk_pid_tbl_usuarios', 'value' => ['gte' => $params['fk_pid_tbl_usuarios'],
  2945. 'lte' => $params['fk_pid_tbl_usuarios'], ]];
  2946. }
  2947. }
  2948.  
  2949. private function setFilterProvinceCapital(&$queryFilters, $params): void
  2950. {
  2951. if (isset($params['province_capital']) && $params['province_capital']) {
  2952. $queryFilters[] = ['type' => 'term', 'field' => 'province_capital', 'value' => $params['province_capital']];
  2953. }
  2954. }
  2955.  
  2956. private function processQueryString($queryString)
  2957. {
  2958. $queryString = $this->eliminarStopWords($queryString);
  2959. $queryString = $this->corrigeKeywords($queryString);
  2960. $queryString = \trim(\utf8_encode($queryString));
  2961.  
  2962. return $queryString;
  2963. }
  2964.  
  2965. private function eliminarStopWords($query)
  2966. {
  2967. $string_sin_stop_words = '';
  2968. $palabras = \explode(' ', $query);
  2969. $stop_words = \array_merge($this->parameters['elastica']['stopwords'], $this->getStopWordsPrecios());
  2970.  
  2971. if (\count($stop_words) > 0) {
  2972. foreach ($palabras as $palabra) {
  2973. $palabra = \trim($palabra);
  2974. if (!\in_array(\mb_strtolower($palabra), $stop_words)) {
  2975. if ($string_sin_stop_words == '') {
  2976. $string_sin_stop_words .= $palabra;
  2977. } else {
  2978. $string_sin_stop_words .= ' ' . $palabra;
  2979. }
  2980. }
  2981. }
  2982. }
  2983.  
  2984. return $string_sin_stop_words;
  2985. }
  2986.  
  2987. private function getStopWordsPrecios()
  2988. {
  2989. include_once PATH_SRC . 'data/daoprog/DAOProg_tbl_filtro_precio.class.php';
  2990.  
  2991. $precios = [];
  2992. $DAOFiltroPrecio = new \DAOProg_tbl_filtro_precio();
  2993. $DAOFiltroPrecio->selectAllFor(DEFAULT_PRICE_TYPE, 'indexable = 1');
  2994. foreach ($DAOFiltroPrecio->aDO as $precio) {
  2995. $precios[] = $precio['precio'];
  2996. }
  2997.  
  2998. return $precios;
  2999. }
  3000.  
  3001. private function corrigeKeywords($query)
  3002. {
  3003. $keywordsCorrections = $this->parameters['elastica']['keywordsCorrections'];
  3004. foreach ($keywordsCorrections as $oldKeyword => $newKeyword) {
  3005. $query = \preg_replace('/' . $oldKeyword . '/', $newKeyword, $query);
  3006. }
  3007.  
  3008. return $query;
  3009. }
  3010.  
  3011. private function getUrl($propertyData)
  3012. {
  3013. include_once PATH_SRC . 'core/' . CARPETA_SMARTY . '/libs/plugins/outputfilter.rewrite_urls.php';
  3014. $url = DOMAIN_NAME . 'index.php/cod.ficha/id.' . $propertyData['id'] . '/po.' . TextUtilities::dirify($propertyData['nombre_pob']) . '/ca.' . TextUtilities::dirify($propertyData['categoria']) . '/tit.' . TextUtilities::dirify($propertyData['titulo']) . '/';
  3015. $url = smarty_outputfilter_rewrite_urls($url, $this);
  3016.  
  3017. return $url;
  3018. }
  3019.  
  3020. private function setFilterAvailabilityDates(&$queryFilters, $params): void
  3021. {
  3022. if (!empty($params['date_from']) || !empty($params['date_to'])) {
  3023. $filter = [
  3024. 'type' => 'nested',
  3025. 'field' => [
  3026. 'path' => 'availability_calendar',
  3027. 'query' => [
  3028. 'bool' => [
  3029. 'must' => [],
  3030. ],
  3031. ],
  3032. ],
  3033. ];
  3034.  
  3035. if (!empty($params['date_from'])) {
  3036. $date = \date('Y-m-d', \strtotime(\str_replace('/', '-', $params['date_from'])));
  3037. $filter['field']['query']['bool']['must'][] = ['range' => ['from' => ['lte' => $date]]];
  3038. }
  3039.  
  3040. if (!empty($params['date_to'])) {
  3041. $date = \date('Y-m-d', \strtotime(\str_replace('/', '-', $params['date_to'])));
  3042. $filter['field']['query']['bool']['must'][] = ['range' => ['to' => ['gte' => $date]]];
  3043. }
  3044.  
  3045. $queryFilters[] = $filter;
  3046. }
  3047. }
  3048.  
  3049. private function setAvailabilityMinimumDays(&$queryFilters, $params): void
  3050. {
  3051. if (!empty($params['date_from']) && !empty($params['date_to'])) {
  3052. $date_from = \DateTime::createFromFormat('d/m/Y', $params['date_from']);
  3053. $date_to = \DateTime::createFromFormat('d/m/Y', $params['date_to']);
  3054.  
  3055. $diff_days = $date_to->diff($date_from);
  3056.  
  3057. $queryFilters[] = [
  3058. 'type' => 'range',
  3059. 'field' => 'booking_availability_minimun_days',
  3060. 'value' => ['lte' => $diff_days->days],
  3061. ];
  3062. }
  3063. }
  3064.  
  3065. private function setFilterPeopleCapacity(&$queryFilters, $params): void
  3066. {
  3067. if (!empty($params['people_capacity'])) {
  3068. $queryFilters[] = ['type' => 'range', 'field' => 'people_capacity', 'value' => ['gte' => (int) $params['people_capacity']]];
  3069. }
  3070. }
  3071.  
  3072. private function setFilterAccesoMinusvalidos(&$queryFilters, $params): void
  3073. {
  3074. if (isset($params['acceso_minusvalidos']) && $params['acceso_minusvalidos']) {
  3075. $queryFilters[] = ['type' => 'term', 'field' => 'acceso_minusvalidos', 'value' => (int) $params['acceso_minusvalidos']];
  3076. }
  3077. }
  3078.  
  3079. private function languages()
  3080. {
  3081. $parameters = DIContainer::getInstance()->get('core.parameters');
  3082.  
  3083. return $parameters['core.supported_languages'];
  3084. }
  3085.  
  3086. private function setFilterHasPositioning($queryFilters, $params): void
  3087. {
  3088. if (isset($params['positioning']) && $params['positioning']) {
  3089. $queryFilters[] = [
  3090. 'type' => 'term',
  3091. 'field' => 'has_positioning',
  3092. 'value' => (int)$params['positioning']
  3093. ];
  3094. }
  3095. }
  3096.  
  3097. private function setFilterSmoker(&$queryFilters, $params): void
  3098. {
  3099. if (isset($params['smoke']) && $params['smoke']) {
  3100. // $smokeFilter[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 1];
  3101. if ($params['smoke'] == self::NOT_SMOKE_FILTER) {
  3102. $queryFilters[] = ['type' => 'term', 'field' => 'smoke', 'value' => 0];
  3103. } else {
  3104. $queryFilters[] = ['type' => 'range', 'field' => 'smoke', 'value' => ['gt' => 0]];
  3105. }
  3106. // $smokeFilterAnd[] = ['type' => 'and', 'field' => 'and_rooms', 'value' => $smokeFilter];
  3107. //
  3108. // $propertyFilter[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 0];
  3109. // $propertyFilterAnd[] = ['type' => 'and', 'field' => 'and_properties', 'value' => $propertyFilter];
  3110. //
  3111. // $queryFilters[] = [
  3112. // 'type' => 'or',
  3113. // 'field' => 'or_tipos',
  3114. // 'value' => array_merge($smokeFilterAnd, $propertyFilterAnd)
  3115. // ];
  3116. }
  3117. }
  3118.  
  3119. private function setFilterRoomerGenderPreference(&$queryFilters, $params): void
  3120. {
  3121. if (isset($params['roomer_gender_preference']) && $params['roomer_gender_preference']) {
  3122. $queryFilters[] = [
  3123. 'type' => 'term',
  3124. 'field' => 'roomer_gender_preference',
  3125. 'value' => (int) $params['roomer_gender_preference']
  3126. ];
  3127. }
  3128. }
  3129.  
  3130. private function setFilterBedSize(&$queryFilters, $params): void
  3131. {
  3132. if (isset($params['bed']) && $params['bed'] && $params['bed'] > 0) {
  3133. $queryFilters[] = ['type' => 'term', 'field' => 'bed', 'value' => (int) $params['bed']];
  3134. }
  3135. }
  3136.  
  3137. private function setFilterRoomSize(&$queryFilters, $params): void
  3138. {
  3139. if (isset($params['room_size']) && $params['room_size'] && $params['room_size'] > 0) {
  3140. $queryFilters[] = ['type' => 'range', 'field' => 'room_size', 'value' => ['gte' => (int) $params['room_size']]];
  3141. }
  3142. }
  3143.  
  3144. private function setFilterPrivateBathroom(&$queryFilters, $params): void
  3145. {
  3146. if (isset($params['private_bathroom']) && $params['private_bathroom']) {
  3147. $queryFilters[] = ['type' => 'term', 'field' => 'private_bathroom', 'value' => (int) $params['private_bathroom']];
  3148. }
  3149. }
  3150.  
  3151. private function setFilterDoorLock(&$queryFilters, $params): void
  3152. {
  3153. if (isset($params['door_lock']) && $params['door_lock']) {
  3154. $queryFilters[] = ['type' => 'term', 'field' => 'door_lock', 'value' => (int) $params['door_lock']];
  3155. }
  3156. }
  3157.  
  3158. private function setFilterFullProperty(&$queryFilters, $params): void
  3159. {
  3160. if (isset($params['full_property']) && $params['full_property']) {
  3161. switch ($params['full_property']) {
  3162. case self::ONLY_FULL_PROPERTY:
  3163. $queryFilters[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 0];
  3164. // $queryFilters[] = [
  3165. // 'type' => 'bool',
  3166. // 'field' => 'must_not',
  3167. // 'value' => [
  3168. // 'term' => ['fk_id_tbl_categorias' => (int) CATEGORY_ROOMS ]
  3169. // ]
  3170. // ];
  3171. break;
  3172. case self::ONLY_ROOMS:
  3173. $queryFilters[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 1];
  3174. // $params['tipo'] = CATEGORY_ROOMS;
  3175. // $queryFilters = $this->removeFilterTipoVivienda($queryFilters);
  3176. // $this->_setFilterTipoVivienda($queryFilters, $params);
  3177. break;
  3178. default:
  3179. break;
  3180. }
  3181. }
  3182. }
  3183.  
  3184. private function removeFilterTipoVivienda($queryFilters)
  3185. {
  3186. $newFilters = [];
  3187. foreach ($queryFilters as $filter) {
  3188. if ($filter['field'] != 'fk_id_tbl_categorias') {
  3189. $newFilters[] = $filter;
  3190. }
  3191. }
  3192.  
  3193. return $newFilters;
  3194. }
  3195. }
Add Comment
Please, Sign In to add comment