<?php
// Perform POST request to given url with given parameters (associative array) and return array of lines
function post_it($datastream, $url) 
{
    $url = preg_replace("@^http://@i", "", $url);
    $host = substr($url, 0, strpos($url, "/"));
    $uri = strstr($url, "/");

    $reqbody = "";
    foreach( $datastream as $key=>$val )
    {
        if (!empty($reqbody)) 
            $reqbody .= "&";
        $reqbody .= $key ."=" . urlencode($val);
    }

    $contentlength = strlen($reqbody);
    $reqheader =  "POST $uri HTTP/1.1\r\n" .
                  "Host: $host\n". "User-Agent: cmdline\r\n" .
                  "Content-Type: application/x-www-form-urlencoded\r\n" .
                  "Content-Length: $contentlength\r\n\r\n" .
                  "$reqbody\r\n";

    $socket = fsockopen($host, 80, $errno, $errstr, 10 );
 
    if( !$socket ) 
    {
       $result["errno"] = $errno;
       $result["errstr"] = $errstr;
 
       return $result;
    }
 
    fputs($socket, $reqheader);
 
    socket_set_timeout( $socket, 30 );

    $sockitem = "noop";

    while( !feof($socket) && !preg_match( '|</html>|i', $sockitem ) ) 
    {
        $sockitem = fgets($socket, 4096);
        $result[] = $sockitem; 
    }
 
    fclose($socket);

    return $result;
}

function trunc($x)
{
    if( $x >= 0.0 )
        return( floor($x) );
    else
        return( ceil($x) );
}

function sign($x)
{
    if( $x > 0.0 )
        return( 1 );
    elseif( $x < 0.0 )
        return( -1 );
    else
        return( 0 );
}

function USNOtimestring($str)
{
    if( preg_match( '/^(1?\d):([0-5]\d)\s+([ap])/', $str, $matches ) )
    {
        if( $matches[3] == "p" )
        {
            if( $matches[1] == "12" )
            {
                $thehour = $matches[1];
            }
            else
            {
                $thehour = 12 + $matches[1];
            }
        }
        elseif( $matches[1] == "11" || $matches[1] == "10" )
        {
            $thehour = $matches[1];
        }
        elseif( $matches[1] == "12" )
        {
            $thehour = "00";
        }
        else
        {
            $thehour = "0" . $matches[1];
        }
                
        return( "$thehour$matches[2]" );
     }

    return( "" );
}

function USNOmoonday($str)
{
    if( preg_match( '/on (preceding|following) day/', $str, $matches ) )
    {
        return( substr( $matches[1], 0, 1 ) );
    }

    return( "" );
}

// Today

$longdate = date("D d M Y");
$shortdate = date("d M Y");

$year  = date("Y");
$month = date("n");
$day   = date("j");
$dst   = date("I");

$today = getdate();
$utyear  = gmdate("Y");
$utmonth = gmdate("n");
$utday   = gmdate("j");
$utseconds = gmdate("s");
$utseconds = "1$utseconds" - 100;
$utminutes = gmdate("i");
$utminutes = "1$utminutes" - 100;
$uthours = gmdate( "G" ) + 0;

$jd = cal_to_jd( CAL_GREGORIAN, $utmonth, $utday, $utyear ) + (($uthours + $utminutes/60 + $utseconds/3600)/24) - 0.5; 
$jd_usno = 367*$utyear - trunc( (7 * ($utyear + trunc(($utmonth+9)/12)))/4 ) + trunc((275 * $utmonth)/9) + $utday + 1721014.0 + (($uthours + $utminutes/60 + $utseconds/3600)/24) - 0.5*sign(100*$utyear + $utmonth - 190002.5);
// JD = 367K - <(7(K+<(M+9)/12>))/4> + <(275M)/9> + I + 1721013.5 + UT/24 - 0.5sign(100K+M-190002.5) + 0.5 


// Read Sun Moon info from USNO and set a cookie so we only probe once a day

$smcookie_exptime = mktime( 0, 0, 0, $month, $day, $year, $dst ) + 24*3600;
$smcookie_value   = "";

$smdata["st"] = "PA";
$smdata["place"] = "Pittsburgh";
$smdata["xxy"] = $year;
$smdata["xxm"] = $month;
$smdata["xxd"] = $day;
$smdata["FFX"] = 1;
$smdata["ID"] = "cmdline";
$smdata["ZZZ"] = "END";

echo "{$smdata['st']}\n";
echo "{$smdata['place']}\n";
echo "{$smdata['xxy']}\n";
echo "{$smdata['xxm']}\n";
echo "{$smdata['xxd']}\n";
echo "{$smdata['FFX']}\n";
echo "{$smdata['ID']}\n";
echo "{$smdata['ZZZ']}\n";

 

$result = post_it($smdata, "http://aa.usno.navy.mil/cgi-bin/aa_pap.pl");

if( isset($result["errno"]) ) 
{
    $smerrno = $result["errno"];
    $smerrstr = $result["errstr"];
    echo "<B>Error $errno</B> $errstr";
    exit;
} 
else 
{
    // Want the latest risetime before next day's morning twilight
    // and latest set time after evening twilight (and rise time?)
    // these record best state so far for each

    $sm_best_rise_time = "0000";
    $sm_best_rise_ndpd = "";
    $sm_best_set_time = "0900";
    $sm_best_set_ndpd = "f";
    $sm_moonrise_set = 0;
    $sm_moonset_set = 0;
    
    $sm_close_set_dist = "2400";
    $sm_close_set_time = "----";
    $sm_close_rise_dist = "2400";
    $sm_close_rise_time = "----";

    for( $i=0; $i < count($result); $i++ )
    {
        echo "[[[{$result[$i]}]]]\n";
        continue;

        if( preg_match( '/Begin civil twilight\s*(\S.*\.)/', $result[$i], $matches ) )
            $smoutput["mtwilight"] = USNOtimestring($matches[1]);
        elseif( preg_match( '/Sunrise\s*(\S.*\.)/', $result[$i], $matches ) )  
            $smoutput["sunrise"] = USNOtimestring($matches[1]);
        elseif( preg_match( '/Sunset\s*(\S.*\.)/', $result[$i], $matches ) )  
            $smoutput["sunset"] = USNOtimestring($matches[1]);
        elseif( preg_match( '/End civil twilight\s*(\S.*\.)/', $result[$i], $matches ) )
            $smoutput["etwilight"] = USNOtimestring($matches[1]);
        elseif( preg_match( '/Moonrise\s*(\S.*\S)/', $result[$i], $matches ) )  
        {
            $moonstring = $matches[1];
            $ndpd = USNOmoonday($moonstring);
            $moontime = USNOtimestring($moonstring);

            if( ($ndpd == "" ) && ($moontime > $smoutput["etwilight"]) )
            {
                if( ($sm_best_rise_ndpd == "") && ($moontime > $sm_best_rise_time) )
                {
                    $sm_best_rise_time = $moontime;
                    $sm_best_rise_ndpd = $ndpd;
                    $sm_moonrise_set = 1;
                }
            }
            elseif( ($ndpd == "f") && ($moontime < $smoutput["mtwilight"]) )
            {
                if( ($sm_best_rise_ndpd == "") || ($moontime > $sm_best_rise_time) )
                {
                    $sm_best_rise_time = $moontime;
                    $sm_best_rise_ndpd = $ndpd;
                    $sm_moonrise_set = 1;
                }
            }

            if( $sm_moonrise_set == 0  &&  $ndpd != "p" )
            {
                // anything here must be outside twilight interval by construction, so we assume that

                if( (($ndpd == "")  && (($smoutput["etwilight"] - $moontime) < $sm_close_rise_dist)) ||
                    (($ndpd == "f") && (($moontime - $smoutput["mtwilight"]) < $sm_close_rise_dist)) )
                {
                    $sm_close_rise_time = "$moontime " . (($ndpd == "p") ? "[pd]" : (($ndpd == "f") ?  "[nd]" : ""));
                    $sm_close_rise_dist = ($ndpd == "") ? ($smoutput["etwilight"] - $moontime) : ($moontime - $smoutput["mtwilight"]);
                }
            }
        }
        elseif( preg_match( '/Moonset\s*(\S.*\S)/', $result[$i], $matches ) )
        {
            $moonstring = $matches[1];
            $ndpd = USNOmoonday($moonstring);
            $moontime = USNOtimestring($moonstring);

            if( ($ndpd == "" ) && ($moontime > $smoutput["etwilight"]) )
            {
                if( ($sm_best_set_ndpd == "f") || ($moontime < $sm_best_set_time) )
                {
                    $sm_best_set_time = $moontime;
                    $sm_best_set_ndpd = $ndpd;
                    $sm_moonset_set = 1;
                }
            }
            elseif( ($ndpd == "f") && ($moontime < $smoutput["mtwilight"]) )
            {
                if( ($sm_best_set_ndpd == "f") && ($moontime < $sm_best_set_time) )
                {
                    $sm_best_set_time = $moontime;
                    $sm_best_set_ndpd = $ndpd;
                    $sm_moonset_set = 1;
                }
            }

            if( $sm_moonset_set == 0  &&  $ndpd != "p" )
            {
                // anything here must be outside twilight interval by construction, so we assume that

                if( (($ndpd == "")  && (($smoutput["etwilight"] - $moontime) < $sm_close_set_dist)) ||
                    (($ndpd == "f") && (($moontime - $smoutput["mtwilight"]) < $sm_close_set_dist)) )
                {
                    $sm_close_set_time = "$moontime " . (($ndpd == "p") ? "[pd]" : (($ndpd == "f") ?  "[nd]" : ""));
                    $sm_close_set_dist = ($ndpd == "") ? ($smoutput["etwilight"] - $moontime) : ($moontime - $smoutput["mtwilight"]);
                }
            }
        }
        elseif( preg_match( '/Phase.*;\s*(\S.*\S)/', $result[$i], $matches ) )  
            $smoutput["phasename"] =  $matches[1];
        elseif( preg_match( '/with\s*([0-9]+%)/', $result[$i], $matches ) )  
            $smoutput["phase"] = $matches[1];
        elseif( preg_match( '/(New|First [Qq]uarter|Full|Last [Qq]uarter)\s+Moon.*\S/', $result[$i], $matches ) )  
            $smoutput["nextphase"] = $matches[0];
    }

    exit;

    if( $sm_moonrise_set == 1 )
        $smoutput["moonrise"] = "$sm_best_rise_time " . (($sm_best_rise_ndpd == "p") ? "[pd]" : (($sm_best_rise_ndpd == "f") ?  "[nd]" : ""));
    else
        $smoutput["moonrise"] = $sm_close_rise_time;

    if( $sm_moonset_set == 1 )
        $smoutput["moonset"]  = "$sm_best_set_time "  . (($sm_best_set_ndpd == "p")  ? "[pd]" : (($sm_best_set_ndpd == "f")  ?  "[nd]" : ""));
    else
        $smoutput["moonset"]  = $sm_close_set_time;

    $smcookie_value = sprintf( '<TABLE STYLE="font-size: x-small;"><TR><TD colspan=2><A HREF="http://aa.usno.navy.mil/data/docs/RS_OneDay.html">Sun &amp; Moon Data</A></TD></TR><TR><TD>Sun</TD><TD>%s&nbsp;&nbsp;%s&nbsp;&nbsp;%s&nbsp;&nbsp;%s</TD></TR><TR><TD>Moon</TD><TD> %s &nbsp;%s&nbsp;&nbsp;%s</TD></TR><TR><TD colspan=2>%s</TD></TR></TABLE>', $smoutput["mtwilight"], $smoutput["sunrise"], $smoutput["sunset"], $smoutput["etwilight"], $smoutput["phase"], $smoutput["moonrise"], $smoutput["moonset"], $smoutput["nextphase"] );

    $usno_search = array( '/on preceding day\s*/',
                          '/on following day\s*/',
                          '/\s*a\.m\./', 
                          '/\s*p\.m\./',
                          '/[qQ]uarter/',
                          '/at /',
                          '/\s*Moon on/',
                          '/January/',
                          '/February/',
                          '/March/',
                          '/April/',
                          '/June/',
                          '/July/',
                          '/August/',
                          '/September/',
                          '/October/',
                          '/November/',
                          '/December/'  );

    $usno_replace = array( '[pd]',
                           '[nd]',
                           'am',
                           'pm',
                           'Q',
                           '',
                           ' ',
                          'Jan',
                          'Feb',
                          'Mar',
                          'Apr',
                          'Jun',
                          'Jul',
                          'Aug',
                          'Sep',
                          'Oct',
                          'Nov',
                          'Dec'  );

    $smcookie_value = preg_replace( $usno_search, $usno_replace, $smcookie_value );

    echo "$smcookie_value\n";
}

?>

