You are here

function availability_calendar_update_availability in Availability Calendars 7.4

Same name and namespace in other branches
  1. 7.5 availability_calendar.inc \availability_calendar_update_availability()
  2. 7.3 availability_calendar.inc \availability_calendar_update_availability()

Sets the given date range to the given state for the given calendar.

Note that:

  • $from and $to are both inclusive.
  • $from and $to must be ordered.

Parameters

int $cid: Th calendar id.

int $sid: The state id

DateTime $from:

DateTime $to:

boolean $update_changed: Whether to update the changed timestamp field of the calendar. Normally this should be set to true, but when called from availability_calendar_update_multiple_availability() it is set to false to prevent a sequence of similar writes to the field table.

1 call to availability_calendar_update_availability()
availability_calendar_update_multiple_availability in ./availability_calendar.inc
Updates/inserts the states for the given ranges.

File

./availability_calendar.inc, line 553

Code

function availability_calendar_update_availability($cid, $sid, $from, $to, $update_changed = TRUE) {
  if ($update_changed) {
    availability_calendar_update_calendar($cid);
  }

  // Update the already existing dates.
  $count = db_update('availability_calendar_availability')
    ->fields(array(
    'sid' => $sid,
  ))
    ->condition('cid', $cid, '=')
    ->condition('date', array(
    $from
      ->format(AC_ISODATE),
    $to
      ->format(AC_ISODATE),
  ), 'BETWEEN')
    ->execute();

  // Insert the non-existing dates.

  //PHP5.3: $days = $from->diff($to)->days + 1;
  $timestamp_from = (int) $from
    ->format('U');
  $timestamp_to = (int) $to
    ->format('U');
  $days = (int) round(($timestamp_to - $timestamp_from) / (60 * 60 * 24)) + 1;
  if ($count != $days) {

    // Get existing dates to know which ones to insert.
    $existing_availability = availability_calendar_get_availability($cid, $from, $to);
    $values = array(
      'cid' => $cid,
      'date' => NULL,
      'sid' => $sid,
    );
    $insert = db_insert('availability_calendar_availability')
      ->fields(array_keys($values));
    for ($day = clone $from; $day <= $to; $day
      ->modify('+1 day')) {
      $values['date'] = $day
        ->format(AC_ISODATE);
      if (!array_key_exists($values['date'], $existing_availability)) {
        $insert
          ->values($values);
      }
    }
    $insert
      ->execute();
  }
}