<?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( "" );
}
?>
