# Album Plugin:	format/meta
# For info:	'album -plugin_info format/meta'
# For usage:	'album -plugin_usage format/meta'

use strict;

my $DESCRIPTION = << 'DESCRIPTION';
Adds meta tags to the <head> section of album pages.

Thanks to Ty [tyr poczta fm] for the suggestion!
DESCRIPTION

# Use content-* instead of "Content-Language/Script-Type/Style-Type/Type"
my @HTTP_EQUIV = qw(Expires Ext-Cache Imagetoolbar Page-Enter
	Page-Exit Pics-Label Pragmra Keywords Reply-To Content-.* Refresh
	Set-Cookie Site-Enter Site-Exit Window-Target);

# Common optional tags (and their legal content)
# More at: http://www.html-reference.com/META.htm
my %OPTIONAL = (
  Abstract	=> '.*',
  Author	=> '.*',
  Copyright	=> '.*',
  Description	=> '.*',
  Distribution	=> '(Global|Local|IU)',	# (IU = internal use)
  Expires	=> '.*',	# Actually: RFC1123 date, i.e.: "Tue, 01 Jun 1999 19:58:02 GMT"
  Keywords	=> '.*',
  'Content-Language'	=> '..(-..)',	# Actually: RFC1766 compliant languages
  Refresh	=> '\d+;URL=.*',	# X is seconds
  'Revisit-After'	=> '\d+ days',
  Robots	=> '(no)?(index|follow)(,(no)?(index|follow))*',
  );

sub start_plugin {
	my ($opt) = @_;

	# Setup the options
	album::add_option(1, 'keyval', album::OPTION_ARR,
		usage=>"Add a generic key=val pair to the meta tags");

	foreach my $key ( keys %OPTIONAL ) {
		album::add_option(1, lc($key), album::OPTION_STR,
			usage=>"Specify optional $key meta tag");
	}

	album::add_option(1, 'allow_malformed', album::OPTION_BOOL, default=>0,
		usage=>"Allow malformed values for known meta tags");

	# Setup the hooks
	album::hook($opt, 'do_album', \&setup_meta);

	return {
		author => 'David Ljung Madison',
		href => 'http://MarginalHacks.com/',
		version => '1.0',
		description => $DESCRIPTION,
	};
}

# Handle the options
sub meta {
	my ($opt, $key,$val) = @_;
	my $name = grep($key =~ /^$_$/i, @HTTP_EQUIV) ? "http-equiv" : "name";

	# Check key/val if we have a notion of legal content
	my $re = $OPTIONAL{$key};
	if ($re && !album::option($opt, 'allow_malformed')) {
		album::usage($opt,"Bad value for meta tag $key: [$val]\n\t(expected it to match regexp /$re/)\n")
			unless $val =~ /^$re$/i;
	}

	# Quote key & val
	$key =~ s/\'/%27/g;
	$val =~ s/\'/%27/g;

	return "<meta $name='$key' content='$val'>";
}

sub setup_meta {
	my ($opt,$data, undef,  $dir, $album) = @_;

	my @meta;
	my $keyvals = album::option($opt, 'keyval');
	foreach my $keyval ( @$keyvals ) {
		album::usage($opt,"Can't parse keyval (expected key=val):\n\t-keyval $keyval\n")
			unless $keyval =~ /([^=]+)=(.+)/;
		push(@meta,meta($opt,$1,$2));
	}

	foreach my $key ( keys %OPTIONAL ) {
		my $val = album::option($opt, lc($key));
		push(@meta,meta($opt,$key,$val)) if defined $val;
	}

	# Add it to the head
	$data->{head} .= "\n".join("\n",@meta) if @meta;

	# Do the album!
	return 0;
}

# Plugins always end with:
1;
