###########################################################################
#
# HTMLPlug.pm -- basic html plugin
#
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 1999 New Zealand Digital Library Project
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
###########################################################################

# 
# Note that this plugin handles frames only in a very simple way
# i.e. each frame is treated as a separate document. This means
# search results will contain links to individual frames rather
# than linking to the top level frameset.
# There may also be some problems caused by the _parent target
# (it's removed by this plugin)
#

package HTMLPlug;

use BasPlug;
use ghtml;
use unicode;
use util;
use parsargv;
use XMLParser;

sub BEGIN {
    @HTMLPlug::ISA = ('BasPlug');
}

use strict; # every perl program should have this!
no strict 'refs'; # make an exception so we can use variables as filehandles

my $arguments =
    [ { 'name' => "process_exp",
	'desc' => "{BasPlug.process_exp}",
	'type' => "regexp",
	'deft' =>  &get_default_process_exp() },
      { 'name' => "block_exp",
	'desc' => "{BasPlug.block_exp}",
	'type' => 'regexp',
	'deft' =>  &get_default_block_exp() },
      { 'name' => "nolinks",
	'desc' => "{HTMLPlug.nolinks}",
	'type' => "flag" },
      { 'name' => "keep_head",
	'desc' => "{HTMLPlug.keep_head}",
	'type' => "flag" },
      { 'name' => "no_metadata",
	'desc' => "{HTMLPlug.no_metadata}",
	'type' => "flag" },
      { 'name' => "metadata_fields",
	'desc' => "{HTMLPlug.metadata_fields}",
	'type' => "string",
	'deft' => "Title" },
      { 'name' => "hunt_creator_metadata",
	'desc' => "{HTMLPlug.hunt_creator_metadata}",
	'type' => "flag" },
      { 'name' => "file_is_url",
	'desc' => "{HTMLPlug.file_is_url}",
	'type' => "flag" },
      { 'name' => "assoc_files",
	'desc' => "{HTMLPlug.assoc_files}",
	'type' => "regexp",
	'deft' => &get_default_block_exp() },
      { 'name' => "rename_assoc_files",
	'desc' => "{HTMLPlug.rename_assoc_files}",
	'type' => "flag" },
      { 'name' => "title_sub",
	'desc' => "{HTMLPlug.title_sub}",
	'type' => "string", 
	'deft' => "" },
      { 'name' => "description_tags",
	'desc' => "{HTMLPlug.description_tags}",
	'type' => "flag" },
      { 'name' => "no_strip_metadata_html",
	'desc' => "{HTMLPlug.no_strip_metadata_html}",
	'type' => "string",
	'deft' => "",
	'reqd' => "no"}
      ];

my $options = { 'name'     => "HTMLPlug",
		'desc'     => "{HTMLPlug.desc}",
		'abstract' => "no",
		'inherits' => "yes",
		'args'     => $arguments };

sub new {
    my $class = shift (@_);
    my $self = new BasPlug ($class, @_);
    $self->{'plugin_type'} = "HTMLPlug";
    # 14-05-02 To allow for proper inheritance of arguments - John Thompson
    my $option_list = $self->{'option_list'};
    push( @{$option_list}, $options );
    
    if (!parsargv::parse(\@_, 
			 q^nolinks^, \$self->{'nolinks'},
			 q^keep_head^, \$self->{'keep_head'},
			 q^no_metadata^, \$self->{'no_metadata'},
			 q^metadata_fields/.*/Title^, \$self->{'metadata_fields'},
			 q^hunt_creator_metadata^, \$self->{'hunt_creator_metadata'},
			 q^w3mir^, \$self->{'w3mir'},
			 q^file_is_url^, \$self->{'file_is_url'},
			 q^assoc_files/.*/(?i)\.(jpe?g|jpe|gif|png|css)$^, \$self->{'assoc_files'},
			 q^rename_assoc_files^, \$self->{'rename_assoc_files'},
			 q^title_sub/.*/^, \$self->{'title_sub'},
			 q^description_tags^, \$self->{'description_tags'},
			 q^no_strip_metadata_html/.*/^, \$self->{'no_strip_metadata_html'},
			 "allow_extra_options")) {

	print STDERR "\nIncorrect options passed to HTMLPlug, check your collect.cfg configuration file\n";
	$self->print_txt_usage("");  # Use default resource bundle
	die "\n";
    }

    # retain this for backward compatibility (w3mir option was replaced by
    # file_is_url)
    if ($self->{'w3mir'}) {
	$self->{'file_is_url'} = 1;
    }
    
    $self->{'aux_files'} = {};
    $self->{'dir_num'} = 0;
    $self->{'file_num'} = 0;

    return bless $self, $class;
}

# may want to use (?i)\.(gif|jpe?g|jpe|png|css|js(?:@.*)?)$
# if have eg <script language="javascript" src="img/lib.js@123">
sub get_default_block_exp {
    my $self = shift (@_);
    
    return q^(?i)\.(gif|jpe?g|jpe|jpg|png|css)$^;
}

sub get_default_process_exp {
    my $self = shift (@_);
    
    # the last option is an attempt to encode the concept of an html query ...
    return q^(?i)(\.html?|\.shtml|\.shm|\.asp|\.php\d?|\.cgi|.+\?.+=.*)$^;
}

sub store_block_files
{
    my $self =shift (@_);
    my ($filename) = @_;
    my $html_fname = $filename;
    my @file_blocks;
    
    my ($language, $encoding) = $self->textcat_get_language_encoding ($filename);
	
    # read in file ($text will be in utf8)
    my $text = "";
    $self->read_file ($filename, $encoding, $language, \$text);
    my $textref = \$text;
    my $opencom = '(?:<!--|&lt;!(?:&mdash;|&#151;|--))';
    my $closecom = '(?:-->|(?:&mdash;|&#151;|--)&gt;)';
    $$textref =~ s/$opencom(.*?)$closecom//gs;

    my $attval = "\\\"[^\\\"]+\\\"|[^\\s>]+";
    my @img_matches = ($$textref =~ m/<img[^>]*?src\s*=\s*($attval)[^>]*>/igs);
    my @usemap_matches = ($$textref =~ m/<img[^>]*?usemap\s*=\s*($attval)[^>]*>/igs);
    my @link_matches = ($$textref =~ m/<link[^>]*?href\s*=\s*($attval)[^>]*>/igs);
    my @embed_matches = ($$textref =~ m/<embed[^>]*?src\s*=\s*($attval)[^>]*>/igs);

    foreach my $link (@img_matches, @usemap_matches, @link_matches, @embed_matches) {

	# remove quotes from link at start and end if necessary
	if ($link=~/^\"/) {
	    $link=~s/^\"//;
	    $link=~s/\"$//;
	}

	$link =~ s/\#.*$//s; # remove any anchor names, e.g. foo.html#name becomes foo.html

	if ($link !~ m@^/@ && $link !~ m/^([A-Z]:?)\\/) {
	    # Turn relative file path into full path
	    my $dirname = &File::Basename::dirname($filename);
	    $link = &util::filename_cat($dirname, $link);
	}
	$link = $self->eval_dir_dots($link);
	
	$self->{'file_blocks'}->{$link} = 1;
    }
}

  
# do plugin specific processing of doc_obj
sub process {
    my $self = shift (@_);
    my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
    my $outhandle = $self->{'outhandle'};

    print STDERR "<Processing n='$file' p='HTMLPlug'>\n" if ($gli);

    print $outhandle "HTMLPlug: processing $file\n"
	if $self->{'verbosity'} > 1;

    if ($ENV{'GSDLOS'} =~ /^windows/i) {
      # this makes life so much easier... perl can cope with unix-style '/'s.
      $base_dir =~ s@(\\)+@/@g;
      $file =~ s@(\\)+@/@g; 
    }

    # reset per-doc stuff...
    $self->{'aux_files'} = {};
    $self->{'dir_num'} = 0;
    $self->{'file_num'} = 0;

    my $cursection = $doc_obj->get_top_section();

    $self->extract_metadata ($textref, $metadata, $doc_obj, $cursection)
	unless $self->{'no_metadata'} || $self->{'description_tags'};

    # Store URL for page as metadata - this can be used for an
    # altavista style search interface. The URL won't be valid
    # unless the file structure contains the domain name (i.e.
    # like when w3mir is used to download a website).
    my $web_url = "http://$file";
    $doc_obj->add_metadata($cursection, "URL", $web_url);
    $doc_obj->add_metadata($cursection, "weblink", "<a href=\"$web_url\">");
    $doc_obj->add_metadata($cursection, "webicon", "_iconworld_");
    $doc_obj->add_metadata($cursection, "/weblink", "</a>");

    if ($self->{'description_tags'}) {
	# remove the html header - note that doing this here means any
	# sections defined within the header will be lost (so all <Section>
	# tags must appear within the body of the HTML)
	my ($head_keep) = ($$textref =~ m/^(.*?)<body[^>]*>/is);

	$$textref =~ s/^.*?<body[^>]*>//is;
	$$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;

	my $opencom = '(?:<!--|&lt;!(?:&mdash;|&#151;|--))';
	my $closecom = '(?:-->|(?:&mdash;|&#151;|--)&gt;)';

	my $lt = '(?:<|&lt;)';
	my $gt = '(?:>|&gt;)';
	my $quot = '(?:"|&quot;|&rdquo;|&ldquo;)';

	my $dont_strip = '';
	if ($self->{'no_strip_metadata_html'}) {
	    ($dont_strip = $self->{'no_strip_metadata_html'}) =~ s{,}{|}g;
	}

	my $found_something = 0; my $top = 1;
	while ($$textref =~ s/^(.*?)$opencom(.*?)$closecom//s) {
	    my $text = $1;
	    my $comment = $2;
	    if (defined $text) {
		# text before a comment - note that getting to here
		# doesn't necessarily mean there are Section tags in
		# the document
		$self->process_section(\$text, $base_dir, $file, $doc_obj, $cursection);
	    }
	    while ($comment =~ s/$lt(.*?)$gt//s) {
		my $tag = $1;
		if ($tag eq "Section") {
		    $found_something = 1;
		    $cursection = $doc_obj->insert_section($doc_obj->get_end_child($cursection)) unless $top;
		    $top = 0;
		} elsif ($tag eq "/Section") {
		    $found_something = 1;
		    $cursection = $doc_obj->get_parent_section ($cursection);
		} elsif ($tag =~ /^Metadata name=$quot(.*?)$quot/s) {
		    my $metaname = $1;
		    my $accumulate = $tag =~ /mode=${quot}accumulate${quot}/ ? 1 : 0;
		    $comment =~ s/^(.*?)$lt\/Metadata$gt//s;
		    my $metavalue = $1;
		    $metavalue =~ s/^\s+//;
		    $metavalue =~ s/\s+$//;
                    # assume that no metadata value intentionally includes
                    # carriage returns or HTML tags (if they're there they
                    # were probably introduced when converting to HTML from
                    # some other format).
		    # actually some people want to have html tags in their
		    # metadata.
		    $metavalue =~ s/[\cJ\cM]/ /sg;
		    $metavalue =~ s/<[^>]+>//sg
			unless $dont_strip && ($dont_strip eq 'all' || $metaname =~ /^($dont_strip)$/);
		    $metavalue =~ s/\s+/ /sg;
		    if ($accumulate) {
			$doc_obj->add_utf8_metadata($cursection, $metaname, $metavalue);
		    } else {
			$doc_obj->set_utf8_metadata_element($cursection, $metaname, $metavalue);	
		    }
		} elsif ($tag eq "Description" || $tag eq "/Description") {
		    # do nothing with containing Description tags
		} else {
		    # simple HTML tag (probably created by the conversion
		    # to HTML from some other format) - we'll ignore it and
		    # hope for the best ;-)
		}
	    }
	}
	if ($cursection ne "") {
	    print $outhandle "HTMLPlug: WARNING: $file contains unmatched <Section></Section> tags\n";
	}

	$$textref =~ s/^.*?<body[^>]*>//is;
	$$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
	if ($$textref =~ /\S/) {
	    if (!$found_something) {
		if ($self->{'verbosity'} > 2) {
		    print $outhandle "HTMLPlug: WARNING: $file appears to contain no Section tags so\n";
		    print $outhandle "          will be processed as a single section document\n";
		}

		# go ahead and process single-section document
		$self->process_section($textref, $base_dir, $file, $doc_obj, $cursection);

		# if document contains no Section tags we'll go ahead
		# and extract metadata (this won't have been done
		# above as the -description_tags option prevents it)
		my $complete_text = $head_keep.$doc_obj->get_text($cursection);
		$self->extract_metadata (\$complete_text, $metadata, $doc_obj, $cursection) 
		    unless $self->{'no_metadata'};

	    } else {
		print $outhandle "HTMLPlug: WARNING: $file contains the following text outside\n";
		print $outhandle "          of the final closing </Section> tag. This text will\n";
		print $outhandle "          be ignored.";

		my ($text);
		if (length($$textref) > 30) {
		    $text = substr($$textref, 0, 30) . "...";
		} else {
		    $text = $$textref;
		}
		$text =~ s/\n/ /isg;
		print $outhandle " ($text)\n";
	    }
	} elsif (!$found_something) {

	    if ($self->{'verbosity'} > 2) {
		# may get to here if document contained no valid Section
		# tags but did contain some comments. The text will have
		# been processed already but we should print the warning
		# as above and extract metadata
		print $outhandle "HTMLPlug: WARNING: $file appears to contain no Section tags and\n";
		print $outhandle "          is blank or empty.  Metadata will be assigned if present.\n";
	    }

	    my $complete_text = $head_keep.$doc_obj->get_text($cursection);
	    $self->extract_metadata (\$complete_text, $metadata, $doc_obj, $cursection) 
		unless $self->{'no_metadata'};
	}
	
    } else {

	# remove header and footer
	if (!$self->{'keep_head'} || $self->{'description_tags'}) {
	    $$textref =~ s/^.*?<body[^>]*>//is;
	    $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
	}

	# single section document
	$self->process_section($textref, $base_dir, $file, $doc_obj, $cursection);
    }
    return 1;
}

# note that process_section may be called multiple times for a single
# section (relying on the fact that add_utf8_text appends the text to any
# that may exist already).
sub process_section {
    my $self = shift (@_);
    my ($textref, $base_dir, $file, $doc_obj, $cursection) = @_;
    # trap links
    if (!$self->{'nolinks'}) {

	# usemap="./#index" not handled correctly => change to "#index"
	$$textref =~ s/(<img[^>]*?usemap\s*=\s*\"?)([^\">\s]+)(\"?[^>]*>)/
	    $self->replace_usemap_links($1, $2, $3)/isge;

	$$textref =~ s/(<(?:a|area|frame|link|script)\s+[^>]*?\s*(?:href|src)\s*=\s*\"?)([^\">\s]+)(\"?[^>]*>)/
	    $self->replace_href_links ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
    }

    # trap images

    # allow spaces if inside quotes - jrm21
    $$textref =~ s/(<(?:img|embed)[^>]*?src\s*=\s*)(\"[^\"]+\"|[^\s>]+)([^>]*>)/
	$self->replace_images ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;

    # add text to document object
    # turn \ into \\ so that the rest of greenstone doesn't think there
    # is an escape code following. (Macro parsing loses them...)
    $$textref =~ s/\\/\\\\/go;
    $doc_obj->add_utf8_text($cursection, $$textref);
}

sub replace_images {
    my $self = shift (@_);
    my ($front, $link, $back, $base_dir, 
	$file, $doc_obj, $section) = @_;

    # remove quotes from link at start and end if necessary
    if ($link=~/^\"/) {
	$link=~s/^\"//;$link=~s/\"$//;
	$front.='"';
	$back="\"$back";
    }

    $link =~ s/\n/ /g;

    # Hack to overcome Windows wv 0.7.1 bug that causes embedded images to be broken
    # If the Word file path has spaces in it, wv messes up and you end up with
    #   absolute paths for the images, and without the "file://" prefix
    # So check for this special case and massage the data to be correct
    if ($ENV{'GSDLOS'} =~ /^windows/i && $self->{'plugin_type'} eq "WordPlug" && $link =~ /^[A-Za-z]\:\\/) {
	$link =~ s/^.*\\([^\\]+)$/$1/;
    }

    my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);

    my $img_file =  $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section);

    my $anchor_name = $img_file;
    $anchor_name =~ s/^.*\///;
    $anchor_name = "<a name=\"$anchor_name\">";

    return $front . $img_file . $back . $anchor_name;
}

sub replace_href_links {
    my $self = shift (@_);
    my ($front, $link, $back, $base_dir, $file, $doc_obj, $section) = @_;

    # attempt to sort out targets - frames are not handled 
    # well in this plugin and some cases will screw things
    # up - e.g. the _parent target (so we'll just remove 
    # them all ;-)
    $front =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
    $back =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
    $front =~ s/target=\"?_parent\"?//is;
    $back =~ s/target=\"?_parent\"?//is;

    return $front . $link . $back if $link =~ /^\#/s;
    $link =~ s/\n/ /g;

    my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
    # href may use '\'s where '/'s should be on Windows
    $href =~ s/\\/\//g;

    my ($filename) = $href =~ /^(?:.*?):(?:\/\/)?(.*)/;
    

    ##### leave all these links alone (they won't be picked up by intermediate 
    ##### pages). I think that's safest when dealing with frames, targets etc.
    ##### (at least until I think of a better way to do it). Problems occur with
    ##### mailto links from within small frames, the intermediate page is displayed
    ##### within that frame and can't be seen. There is still potential for this to
    ##### happen even with html pages - the solution seems to be to somehow tell
    ##### the browser from the server side to display the page being sent (i.e. 
    ##### the intermediate page) in the top level window - I'm not sure if that's 
    ##### possible - the following line should probably be deleted if that can be done
    return $front . $link . $back if $href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/is;


    if (($rl == 0) || ($filename =~ /$self->{'process_exp'}/) || 
	($href =~ /\/$/) || ($href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/i)) {
	&ghtml::urlsafe ($href);
	return $front . "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part . $back;
    } else {
	# link is to some other type of file (eg image) so we'll
	# need to associate that file
	return $front . $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) . $back;
    }
}

sub add_file {
    my $self = shift (@_);
    my ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) = @_;
    my ($newname);

    my $filename = $href;
    $filename =~ s/^[^:]*:\/\///;
    $filename = &util::filename_cat($base_dir, $filename);
       
    # Replace %20's in URL with a space if required. Note that the filename
    # may include the %20 in some situations
    if ($filename =~ /\%20/) {
	if (!-e $filename) {
	    $filename =~ s/\%20/ /g;
	}
    }

    my ($ext) = $filename =~ /(\.[^\.]*)$/;

    if ($rl == 0) {
	if ((!defined $ext) || ($ext !~ /$self->{'assoc_files'}/)) {
	    return "_httpextlink_&rl=0&el=prompt&href=" . $href . $hash_part;
	}
	else {
	    return "_httpextlink_&rl=0&el=direct&href=" . $href . $hash_part;
	}
    }

    if ((!defined $ext) || ($ext !~ /$self->{'assoc_files'}/)) {
	return "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part;
    }
    if ($self->{'rename_assoc_files'}) {
	if (defined $self->{'aux_files'}->{$href}) {
	    $newname = $self->{'aux_files'}->{$href}->{'dir_num'} . "/" .
		$self->{'aux_files'}->{$href}->{'file_num'} . $ext;
	} else {
	    $newname = $self->{'dir_num'} . "/" . $self->{'file_num'} . $ext;
	    $self->{'aux_files'}->{$href} = {'dir_num' => $self->{'dir_num'}, 'file_num' => $self->{'file_num'}};
	    $self->inc_filecount ();
	}
	$doc_obj->associate_file($filename, $newname, undef, $section);
	return "_httpdocimg_/$newname";
    } else {
	($newname) = $filename =~ /([^\/\\]*)$/;
	$doc_obj->associate_file($filename, $newname, undef, $section);
	return "_httpdocimg_/$newname";
    }
}


sub format_link {
    my $self = shift (@_);
    my ($link, $base_dir, $file) = @_;

    my ($before_hash, $hash_part) = $link =~ /^([^\#]*)(\#?.*)$/;
    
    $hash_part = "" if !defined $hash_part;
    if (!defined $before_hash || $before_hash !~ /[\w\.\/]/) {
	my $outhandle = $self->{'outhandle'};
	print $outhandle "HTMLPlug: ERROR - badly formatted tag ignored ($link)\n"
	    if $self->{'verbosity'};
	return ($link, "", 0);
    }

    if ($before_hash =~ s@^((?:http|ftp|file)://)@@i) {
	my $type = $1;

	if ($link =~ /^(http|ftp):/i) {
	    # Turn url (using /) into file name (possibly using \ on windows)
	    my @http_dir_split = split('/', $before_hash);
	    $before_hash = &util::filename_cat(@http_dir_split);
	}

	$before_hash = $self->eval_dir_dots($before_hash);
					 
	my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
	
	my $rl = 0;
	$rl = 1 if (-e $linkfilename);

	# make sure there's a slash on the end if it's a directory
	if ($before_hash !~ /\/$/) {
	    $before_hash .= "/" if (-d $linkfilename);
	}

	return ($type . $before_hash, $hash_part, $rl);
    
    } elsif ($link !~ /^(mailto|news|gopher|nntp|telnet|javascript):/i) {
	if ($before_hash =~ s@^/@@ || $before_hash =~ /\\/) {

	    # the first directory will be the domain name if file_is_url
	    # to generate archives, otherwise we'll assume all files are
	    # from the same site and base_dir is the root

	    if ($self->{'file_is_url'}) {
		my @dirs = split /[\/\\]/, $file;
		my $domname = shift (@dirs);
		$before_hash = &util::filename_cat($domname, $before_hash);
		$before_hash =~ s@\\@/@g; # for windows
	    }
	    else
	    {
		# see if link shares directory with source document
		# => turn into relative link if this is so!
		
		if ($ENV{'GSDLOS'} =~ /^windows/i) {
		    # too difficult doing a pattern match with embedded '\'s...
		    my $win_before_hash=$before_hash;
		    $win_before_hash =~ s@(\\)+@/@g;
		    # $base_dir is already similarly "converted" on windows.
		    if ($win_before_hash =~ s@^$base_dir/@@o) {
		      # if this is true, we removed a prefix
		      $before_hash=$win_before_hash;
		    }
		}
		else {
		    # before_hash has lost leading slash by this point,
		    # -> add back in prior to substitution with $base_dir
		    $before_hash = "/$before_hash"; 

		    $before_hash = &util::filename_cat("",$before_hash);
		    $before_hash =~ s@^$base_dir/@@;
		}
	    }
	} else {
	    # Turn relative file path into full path
	    my $dirname = &File::Basename::dirname($file);
	    $before_hash = &util::filename_cat($dirname, $before_hash);
	    $before_hash = $self->eval_dir_dots($before_hash);
	}

	my $linkfilename = &util::filename_cat ($base_dir, $before_hash); 
	# make sure there's a slash on the end if it's a directory
	if ($before_hash !~ /\/$/) {
	    $before_hash .= "/" if (-d $linkfilename);
	}
	return ("http://" . $before_hash, $hash_part, 1);
    } else {
	# mailto, news, nntp, telnet, javascript or gopher link
	return ($before_hash, "", 0);
    }
}

sub extract_first_NNNN_characters {
    my $self = shift (@_);
    my ($textref, $doc_obj, $thissection) = @_;
    
    foreach my $size (split /,/, $self->{'first'}) {
	my $tmptext =  $$textref;
	# skip to the body
	$tmptext =~ s/.*<body[^>]*>//i;
	# remove javascript
	$tmptext =~ s@<script.*?</script>@ @sig;
	$tmptext =~ s/<[^>]*>/ /g;
	$tmptext =~ s/&nbsp;/ /g;
	$tmptext =~ s/^\s+//;
	$tmptext =~ s/\s+$//;
	$tmptext =~ s/\s+/ /gs;
	$tmptext = &unicode::substr ($tmptext, 0, $size);
	$tmptext =~ s/\s\S*$/&#8230;/; # adds an ellipse (...)
	$doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
    }
}


sub extract_metadata {
    my $self = shift (@_);
    my ($textref, $metadata, $doc_obj, $section) = @_;
    my $outhandle = $self->{'outhandle'};
    # if we don't want metadata, we may as well not be here ...
    return if (!defined $self->{'metadata_fields'});

    # metadata fields to extract/save. 'key' is the (lowercase) name of the
    # html meta, 'value' is the metadata name for greenstone to use
    my %find_fields = ();

    my %creator_fields = (); # short-cut for lookups


    foreach my $field (split /,/, $self->{'metadata_fields'}) {
	# support tag<tagname>
	if ($field =~ /^(.*?)<(.*?)>$/) {
	    # "$2" is the user's preferred gs metadata name
	    $find_fields{lc($1)}=$2; # lc = lowercase
	} else { # no <tagname> for mapping
	    # "$field" is the user's preferred gs metadata name
	    $find_fields{lc($field)}=$field; # lc = lowercase
	}
    }

    if (defined $self->{'hunt_creator_metadata'} &&
	$self->{'hunt_creator_metadata'} == 1 ) {
	my @extra_fields =
	    (
	     'author',
	     'author.email',
	     'creator',
	     'dc.creator',
	     'dc.creator.corporatename',
	     );

	# add the creator_metadata fields to search for
	foreach my $field (@extra_fields) {
	    $creator_fields{$field}=0; # add to lookup hash
	}
    }


    # find the header in the html file, which has the meta tags
    $$textref =~ m@<head>(.*?)</head>@si;

    my $html_header=$1;
    # go through every <meta... tag defined in the html and see if it is
    # one of the tags we want to match.

    # special case for title - we want to remember if its been found
    my $found_title = 0;
    # this assumes that ">" won't appear. (I don't think it's allowed to...)
    $html_header =~ /^/; # match the start of the string, for \G assertion
 
    while ($html_header =~ m/\G.*?<meta(.*?)>/sig) {
	my $metatag=$1;
	my ($tag, $value);

	# find the tag name
	$metatag =~ /(?:name|http-equiv)\s*=\s*([\"\'])?(.*?)\1/is;
	$tag=$2;
	# in case they're not using " or ', but they should...
	if (! $tag) {
	    $metatag =~ /(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
	    $tag=$1;
	}

	if (!defined $tag) {
	    print $outhandle "HTMLPlug: can't find NAME in \"$metatag\"\n";
	    next;
	}

	# don't need to assign this field if it was passed in from a previous 
	# (recursive) plugin
	if (defined $metadata->{$tag}) {next}

	# find the tag content
	$metatag =~ /content\s*=\s*([\"\'])?(.*?)\1/is;
	$value=$2;
	if (! $value) {
	    $metatag =~ /(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
	    $value=$1;
	}
	if (!defined $value) {
	    print $outhandle "HTMLPlug: can't find VALUE in \"$metatag\"\n";
	    next;
	}

	# clean up and add
	$value =~ s/\s+/ /gs;
	chomp($value); # remove trailing \n, if any
	if (exists $creator_fields{lc($tag)}) {
	    # map this value onto greenstone's "Creator" metadata
	    $tag='Creator';
	} elsif (!exists $find_fields{lc($tag)}) {
	    next; # don't want this tag
	} else {
	    # get the user's preferred capitalisation
	    $tag = $find_fields{lc($tag)};
	}
	if (lc($tag) eq "title") {
	    $found_title = 1;
	}
	print $outhandle " extracted \"$tag\" metadata \"$value\"\n" 
	    if ($self->{'verbosity'} > 2);
	$doc_obj->add_utf8_metadata($section, $tag, $value);

    }
    
    # TITLE: extract the document title
    if (exists $find_fields{'title'} && !$found_title) {
	# we want a title, and didn't find one in the meta tags
	# see if there's a <title> tag
	my $title;
	my $from = ""; # for debugging output only
	if ($html_header =~ /<title[^>]*>([^<]+)<\/title[^>]*>/is) {
	    $title = $1;
	    $from = "<title> tags";
	}

	if (!defined $title) {
	    $from = "first 100 chars";
	    # if no title use first 100 or so characters
	    $title = $$textref;
	    $title =~ s/^\xFE\xFF//; # Remove unicode byte order mark	    
	    $title =~ s/^.*?<body>//si;
	    # ignore javascript!
	    $title =~ s@<script.*?</script>@ @sig;
	    $title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
	    $title =~ s/<[^>]*>/ /g; # remove all HTML tags
	    $title = substr ($title, 0, 100);
	    $title =~ s/\s\S*$/.../;
	}
	$title =~ s/<[^>]*>/ /g; # remove html tags
	$title =~ s/&nbsp;/ /g;
	$title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
	$title =~ s/\s+/ /gs; # collapse multiple spaces
	$title =~ s/^\s*//;   # remove leading spaces
	$title =~ s/\s*$//;   # remove trailing spaces

	$title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
	$title =~ s/^\s+//s; # in case title_sub introduced any...
	$doc_obj->add_utf8_metadata ($section, 'Title', $title);
	print $outhandle " extracted Title metadata \"$title\" from $from\n" 
	    if ($self->{'verbosity'} > 2);
    } 
    
    # add FileFormat metadata
    $doc_obj->add_metadata($section,"FileFormat", "HTML");

    # Special, for metadata names such as tagH1 - extracts
    # the text between the first <H1> and </H1> tags into "H1" metadata.

    foreach my $field (keys %find_fields) {
	if ($field !~ /^tag([a-z0-9]+)$/i) {next}
	my $tag = $1;
	if ($$textref =~ m@<$tag[^>]*>(.*?)</$tag[^>]*>@g) {
	    my $content = $1;
	    $content =~ s/&nbsp;/ /g;
	    $content =~ s/<[^>]*>/ /g;
	    $content =~ s/^\s+//;
	    $content =~ s/\s+$//;
	    $content =~ s/\s+/ /gs;
	    if ($content) {
		$tag=$find_fields{"tag$tag"}; # get the user's capitalisation
		$tag =~ s/^tag//i;
		$doc_obj->add_utf8_metadata ($section, $tag, $content);
		print $outhandle " extracted \"$tag\" metadata \"$content\"\n" 
		    if ($self->{'verbosity'} > 2);
	    }
	}
    }    
}


# evaluate any "../" to next directory up
# evaluate any "./" as here
sub eval_dir_dots {
    my $self = shift (@_);
    my ($filename) = @_;
    my $dirsep_os = &util::get_os_dirsep();
    my @dirsep = split(/$dirsep_os/,$filename);

    my @eval_dirs = ();
    foreach my $d (@dirsep) {
	if ($d eq "..") {
	    pop(@eval_dirs);
	    
	} elsif ($d eq ".") {
	    # do nothing!

	} else {
	    push(@eval_dirs,$d);
	}
    }

    # Need to fiddle with number of elements in @eval_dirs if the
    # first one is the empty string.  This is because of a
    # modification to util::filename_cat that supresses the addition
    # of a leading '/' character (or \ if windows) (intended to help
    # filename cat with relative paths) if the first entry in the
    # array is the empty string.  Making the array start with *two*
    # empty strings is a way to defeat this "smart" option.
    #
    if (scalar(@eval_dirs) > 0) {
	if ($eval_dirs[0] eq ""){
	    unshift(@eval_dirs,"");
	}
    }
    return &util::filename_cat(@eval_dirs);
}

sub replace_usemap_links {
    my $self = shift (@_);
    my ($front, $link, $back) = @_;

    $link =~ s/^\.\///;
    return $front . $link . $back;
}

sub inc_filecount {
    my $self = shift (@_);

    if ($self->{'file_num'} == 1000) {
	$self->{'dir_num'} ++;
	$self->{'file_num'} = 0;
    } else {
	$self->{'file_num'} ++;
    }
}


# Extend the BasPlug read_file so that strings like &eacute; are
# converted to UTF8 internally.  
#
# We don't convert &lt; or &gt; or &amp; or &quot; in case
# they interfere with the GML files

sub read_file {
    my ($self, $filename, $encoding, $language, $textref) = @_;

    &BasPlug::read_file($self, $filename, $encoding, $language, $textref);

    # Convert entities to their UTF8 equivalents
    $$textref =~ s/&(lt|gt|amp|quot|nbsp);/&z$1;/go;
    $$textref =~ s/&([^;]+);/&ghtml::getcharequiv($1,1)/gseo;
    $$textref =~ s/&z(lt|gt|amp|quot|nbsp);/&$1;/go;
}

1;
