<?php
  // Constants
  define('CYCLE_LENGTH', 29.530588853);
  define('SECS_PER_DAY', 24 * 60 * 60);

  function get_phase($when) {
    // Find the phase of the moon (as a percentage of its cycle) for the given date
    //  0 == new moon
    $new_time = gmmktime(7, 55, 0, 1, 26, 2009);
    $moon_age = ($when - $new_time) / (CYCLE_LENGTH * SECS_PER_DAY);
    return $moon_age - floor($moon_age);
  }

  // Get the current time and phase
  $now = mktime();
  $phase = get_phase($now);

  // Determine which half of the phase we're in
  if ($phase < 0.5) {
    // Waxing
    $last_name = 'New';
    $next_name = 'Full';
    $last_delta = $phase * CYCLE_LENGTH;
    $next_delta = (0.5 - $phase) * CYCLE_LENGTH;
  } else {
    // Waning
    $last_name = 'Full';
    $next_name = 'New';
    $last_delta = ($phase - 0.5) * CYCLE_LENGTH;
    $next_delta = (1 - $phase) * CYCLE_LENGTH;
  }

  // Calculate time of the next & last events
  $last_time = round(($now - ($last_delta * SECS_PER_DAY)) * 1000);
  $next_time = round(($now + ($next_delta * SECS_PER_DAY)) * 1000);

  // Output the results as XML
  header('Content-Type: text/xml');
  echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<moon>
  <phase type=\"$last_name\">$last_time</phase>
  <phase type=\"$next_name\">$next_time</phase>
</moon>";
?>