You are here

function availability_calendars_handler_filter_availability::query_available in Availability Calendars 6.2

* Add where clauses to the query to filter on availability.

*

Parameters

string $arrival yyyy-mm-dd.: * @param string $departure yyyy-mm-dd.

1 call to availability_calendars_handler_filter_availability::query_available()
availability_calendars_handler_filter_availability::op_between in ./availability_calendars_handler_filter_availability.inc

File

./availability_calendars_handler_filter_availability.inc, line 177

Class

availability_calendars_handler_filter_availability
@class availability_calendars_handler_filter_availability Views handler to filter on availability.

Code

function query_available($arrival, $departure) {
  if (empty($arrival) || empty($departure)) {

    // Don't add a clause if there's nothing to filter on.
    return;
  }
  module_load_include('inc', 'availability_calendars', 'availability_calendars');
  $states = availability_calendars_get_states();
  $settings = availability_calendars_get_settings();
  $default_is_available = $states[$settings->defaultstatus]['is_available'];
  $classes = array();
  foreach ($states as $class => $state) {
    if ($state['is_available'] != $default_is_available) {
      $classes[] = $class;
    }
  }
  $classes = empty($classes) ? '' : "'" . implode("', '", $classes) . "'";

  // Format from and to in a safe way.
  $start = format_date(mktime(12, 0, 0, substr($arrival, 5, 2), substr($arrival, 8, 2), substr($arrival, 0, 4)), 'custom', 'Y-m-d');
  $end = format_date(mktime(12, 0, 0, substr($departure, 5, 2), (int) substr($departure, 8, 2) - 1, substr($departure, 0, 4)), 'custom', 'Y-m-d');

  // Build common part of subquery.
  $base_table_alias = reset($this->query->tables[$this->table]);
  $base_table_alias = $base_table_alias['alias'];
  $from = 'FROM {availability_calendars_day} acd';
  $where = "WHERE acd.nid = {$base_table_alias}.{$this->query->base_field} ";
  $where .= "AND acd.date BETWEEN '{$start}' AND '{$end}' ";
  $where .= "AND acd.status in ({$classes})";
  if ($default_is_available == 1) {

    // Default status = available: so no single day may be marked as non
    // available. Check by doing a check on the existence of a non available
    // day in the given period.
    $subquery = "SELECT 1 {$from} {$where}";
    $this->query
      ->add_where(0, "NOT EXISTS ({$subquery})");
  }
  else {

    // Default status = not available: so all days must be marked as
    // available. Check by doing a count on the available days in the given
    // period which should equal the total number of days.
    $timestamp_arrival = strtotime($arrival);
    $timestamp_departure = strtotime($departure);
    $days = (int) round(($timestamp_departure - $timestamp_arrival) / (60 * 60 * 24));
    $subquery = "SELECT count(*) {$from} {$where}";
    $this->query
      ->add_where(0, "({$subquery}) = {$days}");
  }
}