<?php
/**
 * Handle the FREE-BUSY-QUERY variant of REPORT
 */
include_once("freebusy-functions.php");

$fbq_content = $xmltree->GetContent('urn:ietf:params:xml:ns:caldav:free-busy-query');
$fbq_start = $fbq_content[0]->GetAttribute('start');
$fbq_end   = $fbq_content[0]->GetAttribute('end');
if ( ! ( isset($fbq_start) || isset($fbq_end) ) ) {
  $request->DoResponse( 400, 'All valid freebusy requests MUST contain a time-range filter' );
}

if ( isset($fbq_start) ) {
  $range_start = new RepeatRuleDateTime($fbq_start);
} else {
  # RFC 4791 Section 9.9 says that if start isn't set, then -infinity
  # should be used. We can't specify that in PHP, and
  # expand_event_instances has '-6 weeks' as the default.
  # That's a bit short, go for one year prior to end, if defined,
  # otherwise 1 year prior to now now.
  if ( isset($fbq_end) ) {
    $range_start = new RepeatRuleDateTime($fbq_end);
  } else {
    $range_start = new RepeatRuleDateTime;
  }

  $range_start->modify('-365 days');
}

if ( isset($fbq_end) ) {
  $range_end = new RepeatRuleDateTime($fbq_end);
} else {
  # RFC 4791 Section 9.9 says that if end isn't set, then +infinity
  # should be used. We can't specify that in PHP, and
  # expand_event_instances has '+ 6 weeks' as the default. That's a
  # bit short, go for two years from the start.
  $range_end = clone($range_start);
  $range_end->modify('+730 days');
}

/** We use the same code for the REPORT, the POST and the freebusy GET... */
$freebusy = get_freebusy( '^' . $request->path . $request->DepthRegexTail(true), $range_start, $range_end );

$result = new iCalComponent();
$result->VCalendar();
$result->AddComponent($freebusy);

$request->DoResponse( 200, $result->Render(), 'text/calendar' );
// Won't return from that

