<?php
// Today
date_default_timezone_set('America/New_York');

$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_name = "crgdailysunmoon";

if( !isset($_COOKIE[$smcookie_name]) || !$_COOKIE[$smcookie_name] )
{
    $smcookie_exptime = mktime( 0, 0, 0, $month, $day, $year ) + 24*3600;
    $smcookie_value   = "";

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

    $smdata["fieldset"] = "default";
    $smdata["form.submitted"] = 1;
    $smdata["add_reference.field:record"] = "";
    $smdata["add_reference.type:record"] = "";
    $smdata["add_reference.destination:record"] = "";
    $smdata["last_referer"] = "http://www.usno.navy.mil/USNO/astronomical-applications";
    $smdata["_authenticator"] = "537f28f136972776ee40f21e467d946c566b7a04";
  
    $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++ )
        {
            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];
        }


        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 );
    }

    $smcookiestatus = setcookie( $smcookie_name, base64_encode(gzdeflate($smcookie_value)), $smcookie_exptime );
}


$apodcookie_name = "apoddailythumb";

if( !isset($_COOKIE[$apodcookie_name]) || !$_COOKIE[$apodcookie_name] )
{
    $apodcookie_exptime = mktime( 0, 0, 0, $month, $day, $year ) + 24*3600;
    $apodcookie_value   = "";

    $apod = file_get_contents( "http://antwrp.gsfc.nasa.gov/apod/index.html" );

    if( preg_match( '|\<IMG SRC=\"([^"]+)\".*?alt="[.\s\w]+">\s*</a>\s*</center>.*?<center>\s*<b>\s*([^<]+)|ims', $apod, $matches ) )
    {
        $apodcookie_value = sprintf( '<SPAN STYLE="font-size: x-small;"><A HREF="http://antwrp.gsfc.nasa.gov/apod">APOD</A>&nbsp;%s<BR/></SPAN><A HREF="http://antwrp.gsfc.nasa.gov/apod"><IMG SRC="http://antwrp.gsfc.nasa.gov/apod/%s" WIDTH=200 ALT="APOD Thumbnail Link"/></A>',
                                     ((strlen($matches[2]) <= 32) ? $matches[2] : (substr($matches[2],0,32) . "...")), $matches[1] );
    }
    else
    {
        $apodcookie_value = '<SPAN STYLE="font-size: x-small;"><A HREF="http://antwrp.gsfc.nasa.gov/apod">APOD</A><BR/></SPAN>';
    }

    $apodcookiestatus = setcookie( $apodcookie_name, base64_encode(gzdeflate($apodcookie_value)), $apodcookie_exptime );
    //$apodcookiestatus = setcookie( $apodcookie_name, $apodcookie_value, $apodcookie_exptime ); //DEBUG
}

//to reset cookies manually, uncomment and reload a couple times
//setcookie( $smcookie_name, FALSE );
//setcookie( $apodcookie_name, FALSE );

?>

