#
#	This module support cookie interface for CGI script
#
#	Author: Masaki Ikeda
#	Date:	21 Oct. 1997
#
#	Function(s)
#	CookieParse
#		Read cookie(s) data, converts it to unescape text,
#		and puts one key=value in each member of the list
#		"@in"
#		Returns TRUE if there was cookie(s), FALSE if there was
#		no cookie(s).
#
#	CookieBake
#		Cookie strings bake from Associate array.
#		This function is ONLY 'bake'.
#		Sent to user is YOUR job.:-)
#
#	CookieDate
#		Seconds from 1970-1-1 0:0:0 to Cookie expires format
#		"Sat, 1-Jan-2000 00:00:00 +0900".
#

sub CookieParse {
	local( *in ) = @_ if @_;
	local( $i, $key, $value );

	if( $ENV{'HTTP_COOKIE'} ne "" ) {
		@in = split(/; */, $ENV{'HTTP_COOKIE'});
	}

	foreach $i ( 0 .. $#in ) {
		( $key, $value ) = split( /=/, $in[$i] );
		$key =~ s/%(..)/pack( "c", hex($1))/ge;
		$value =~ s/%(..)/pack( "c", hex($1))/ge;

		$in{$key} = $value;
	}

	return length( $in );
}

sub CookieBake {
	local( *out, $expire ) = @_ if @_;
	local( $i, $key, $value );
	local( $RetStr );
	$expire = &CookieDate( $expire );

	foreach $i ( keys %out ) {
		$key = $i;
		$value = $out{$i};
		$key =~ s/([;, \x80-\xFF])/sprintf("%%%02X", unpack("C", $1))/eg;
		$value =~ s/([;, \x80-\xFF])/sprintf("%%%02X", unpack("C", $1))/eg;
		$RetStr .= "Set-Cookie: $key=$value; expires=$expire; \n";
	}
	return $RetStr;
}

sub CookieDate {
	local( $t ) = @_;
	local( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst )
		= localtime( $t );
	$mon = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'
		,'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' )[$mon];
	$wday = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' )[$wday];
	$year += 1900;
	return sprintf("%s, %d-%s-%d %02d:%02d:%02d +0900"
		, $wday, $mday, $mon, $year, $hour, $min, $sec);
}

1;
