# Blosxom Plugin: metadate
# Author(s): Mark Ivey <zovirl@zovirl.com>
# Version: 0.0.3
# Documentation: See the bottom of this file or type: perldoc metadate

package metadate;

# --- Configurable variables -----

# fullpath to the external metadates file (see perldoc for description)
$external_file = "$blosxom::datadir/external_metadate";

$use_UK_dates = 0;          # Default is mm/dd/yy (US)
                            # Set to 1 to use dd/mm/yy (UK)

# --------------------------------

use English;
use File::Basename;
use Time::Local;
use File::Find;
use File::stat;
use Time::Local;

use vars qw( %dirs, %all );

my $debug = 0;   # log debug messages or not?

sub start 
{
    return 1;
}

# FIXME: make the external metadate file optional
# FIXME: handle both creation date & modification date...

sub filter 
{
    _add_from_find();
    _add_from_file();
    return 1;
}

sub _add_from_file
{
    # read the external metadates file
    unless (open(FILE, "< $external_file"))
    {
        warn "metadate::filter() couldn't open external file $external_file\n"; 
        return 0;
    }
    
    while (<FILE>) 
    {
        next if (/^\s*#/);  # skip comments
        if (/(.*)=>(.*)/)
        {
            my ($file, $time) = ($1, $2);
            $file =~ s!/*$!!;               # remove any trailing slashes
            $file =~ s!^/*!!;               # remove any leading slashes
            $file = "$blosxom::datadir/$file";
            warn "metadate: $file=>$time\n" if $debug > 0;
            
            $time = parsedate($time);
            
            _add($file, $time);
        }
    }
    close(FILE);

    return 1;
}

sub _add_from_find
{
    find(
    	sub {
                _add($File::Find::name, extract_date($File::Find::name,$files{$File::Find::name}) ||
                                        $files{$File::Find::name} ||
                                        stat($File::Find::name)->mtime)
    		},
    	$blosxom::datadir
    );

    return 1;
}

sub _add
{
    my $file = shift or return;
    my $time = shift or return;

    # check %files, then %others, then check for a directory.  Always add to %all
    if (exists $blosxom::files{$file})
    {
        $blosxom::files{$file} = $time;
    }
    elsif (exists $blosxom::others{$file})
    {
        $blosxom::others{$file} = $time;
    }
    elsif (-d "$file")
    {
        $dirs{$file} = $time;
    }

    $all{$file} = $time;
}


# extract_date() taken from Fletcher T. Penney's entriescache plugin
# <http://www.blosxom.com/plugins/indexing/entries_cache.htm>

# FIXME I should make _add_from_file() know about these and then
# make them user variables
$use_date_tags = 1;
$update_meta_date = 0;
$meta_timestamp = "meta-creation_timestamp:" unless defined $meta_timestamp;
$meta_date = "meta-creation_date:" unless defined $meta_date;

sub extract_date {
	my ($file, $indexed_date) = @_;
	my $new_story = "";
	my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst);
	
	# This is an attempt for compatibility with Eric Sherman's entries_index_tagged
	# But it does not handle as many date formats, as there are too many additional
	# necessary modules that I am not willing to require
	
	if ( $use_date_tags != 0) {
	
		open (FILE, $file);

		while ($line = <FILE>) {
			if ($line =~ /^$meta_timestamp\s*(\d+)/) {
				# If present, this format is used
				close File;
				return $1;
			}
			
			if ($line =~ /^$meta_date\s*(.*)/) {
				close File;
				return parsedate($1);
			}
			
			if ($line =~ /^\s*$/) {
				# Empty Line signifying end of meta-tags
				if ($update_meta_date eq 1) {
					if ($indexed_date eq 0) {
						$indexed_date = stat($file)->mtime;
					}
					
					($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($indexed_date);
					$year += 1900;
					$mon += 1;
					$hour = sprintf("%02d",$hour);
					$min = sprintf("%02d",$min);
					$sec = sprintf("%02d",$sec);
				
					if ($use_UK_dates eq 1) {
						$new_story .= "$meta_date $mday/$mon/$year $hour:$min:$sec\n\n";
					} else {
						$new_story .= "$meta_date $mon/$mday/$year $hour:$min:$sec\n\n";
					}
					
					while ($line = <FILE>) {
						$new_story .= $line;
					}
					
					close FILE;
					open (FILE, "> $file") or warn "Unable to update date meta-tag on $file\n";
					print FILE $new_story;
					close FILE;
					return 0;
				} else {
					close File;
					return 0;
				}
			}

			$new_story .= $line;
		}
	}
	return 0;	
}

# parsedate() taken from Fletcher T. Penney's entriescache plugin
# <http://www.blosxom.com/plugins/indexing/entries_cache.htm>
sub parsedate 
{
	my ($datestring) = @_;
	#warn "Parsing $datestring\n";
	
	# Possible formatting
	# Month can be 3 letter abbreviation or full name (in English)
	# Time must be hh:mm or hh:mm:ss  in 24 hour format
	# Year must be yyyy
	# The remaining 1 or 2 digits are treated as date
	# ie: May 25 2003 18:40 
	# order is not important as long as pieces are there
		
	# Convert the datestring to a time() format

	# Find "Shorthand" Date
	if ( $datestring =~ /\d\d?\/\d\d?\/\d\d\d?\d?/) {
		if ( $use_UK_dates eq 0) {
    # Use US Formatting
    $datestring =~ s/(\d\d?)\/(\d\d?)\/(\d\d\d?\d?)//;
    $mon = $1 - 1;
    $day = $2;
    $year = $3;
		} else {
    # Use UK Formatting
    $datestring =~ s/(\d\d?)\/(\d\d?)\/(\d\d\d?\d?)//;
    $mon = $2 - 1;
    $day = $1;
    $year = $3;
		}
		
		# Now, clean up year if 2 digit
		# You may change the 70 to whatever cutoff you like
		$year += 2000 if ($year < 70 );
		$year += 1900 if ($year < 100);
	}
	
	# Find Month
	$mon = 0 if ($datestring =~ s/(Jan|January)//i);
	$mon = 1 if ($datestring =~ s/(Feb|February)//i);
	$mon = 2 if ($datestring =~ s/(Mar|March)//i);
	$mon = 3 if ($datestring =~ s/(Apr|April)//i);
	$mon = 4 if ($datestring =~ s/(May)//i);
	$mon = 5 if ($datestring =~ s/(Jun|June)//i);
	$mon = 6 if ($datestring =~ s/(Jul|July)//i);
	$mon = 7 if ($datestring =~ s/(Aug|August)//i);
	$mon = 8 if ($datestring =~ s/(Sep|September)//i);
	$mon = 9 if ($datestring =~ s/(Oct|October)//i);
	$mon = 10 if ($datestring =~ s/(Nov|November)//i);
	$mon = 11 if ($datestring =~ s/(Dec|December)//i);

	# Find Time
	if ($datestring =~ s/(\d\d?):(\d\d)(:\d\d)?//) {
		$hour = $1;
		$min = $2;
		$sec = $3;
	}
	
	if ($datestring =~ s/(\d\d\d\d)//) {
		$year = $1;
	}
	
	if ($datestring =~ s/(\d\d?)//) {
		$day = $1;
	}
	
	return timelocal($sec,$min,$hour,$day,$mon,$year);
	
}


1;

__END__

=head1 NAME

Blosxom Plug-in: metadate

=head1 SYNOPSIS

Handles meta tags related to dates.

=head1 VERSION

0.0.3

=head1 AUTHOR

Mark Ivey <zovirl@zovirl.com>, http://zovirl.com

=head1 DESCRIPTION

metadate parses metadates in stories.  It also
provides a way to save metadates externally from a file.
This is most useful for non-story files, such as pictures or categories which
can't contain metadates internally.

The file $external_file should contain entries in this format:

 # comment lines start with a "#"
 /software=>11/17/2003 22:45
 /software/screenshot.png=>11/18/2003 22:50
 /software/static_file.patch.asc=>11/18/2003 22:50

WARNING: The file format changed between version 0.0.1 and 0.0.2.  It used
to contain the full path to the file.  Now it contains the path from
$blosxom::datadir, to make it easier to relocate $blosxom::datadir

metadates stores dates in %blosxom::files (for story files), %blosxom::others
(for non-story files), or %metadate::dirs (for directories).  Metdates
also provides %metadates::all, which contains any file/directory metadate knows about.

=head1 SEE ALSO

Blosxom Home/Docs/Licensing: http://www.raelity.org/apps/blosxom/

Blosxom Plugin Docs: http://www.raelity.org/apps/blosxom/plugin.shtml

parsedate() and extract_date() taken from Fletcher T. Penney's entriescache plugin:
http://www.blosxom.com/plugins/indexing/entries_cache.htm

=head1 BUGS

Address bug reports and comments to the Blosxom mailing list 
[http://www.yahoogroups.com/group/blosxom].

=head1 LICENSE

metadate Blosxom Plugin Copyright 2003-2004, Mark Ivey

Portions Copyright 2003, Fletcher Penney

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
