package SWISH::Filter;

use 5.005;
use strict;
use File::Basename;
#use MIME::Types;  # require below
use Carp;
use FindBin;  # for locating libexecdir (mostly under windows)

use vars qw/ $VERSION %extra_methods/;

$VERSION = '0.02';

# Define the available parameters
%extra_methods = map {$_ => 1} qw/name user_data /;



# For testing only

if ( $0 =~ 'Filter.pm' && @ARGV >= 2 && shift =~ /^test/i) {
    die "Please use the 'swish-filter-test' program.\n";
}




=head1 NAME

SWISH::Filter - Perl extension for filtering documents with Swish-e

=head1 SYNOPSIS

  use SWISH::Filter;

  # load available filters into memory
  my $filter = SWISH::Filter->new;


  # convert a document

  my $doc = $filter->convert(
        document     => \$scalar_ref,  # path or ref to a doc
        content_type => $content_type, # content type if doc reference
        name         => $real_path,    # optional name for this file (useful for debugging)
        user_data    => $whatever,     # optional data to make available to filters
   );

  return unless $doc;  # empty doc, zero size, or no filters installed

  # Was the document converted by a filter?
  my $was_filtered = $doc->was_filtered;

  # Skip if the file is not text
  return if $doc->is_binary;

  # Print out the doc
  my $doc_ref = $doc->fetch_doc;
  print $$doc_ref;

  # Fetch the final content type of the document
  my $content_type = $doc->content_type;

  # Fetch Swish-e parser type (TXT*, XML*, HTML*, or undefined)
  my $doc_type = $doc->swish_parser_type;

=head1 DESCRIPTION

SWISH::Filter provides a unified way to convert documents into a type that
Swish-e can index.  Individual filters are installed as separate perl modules.
For example, there might be a filter that converts from PDF format to HTML
format.

Note that this is just a framework for filtering documents.  Additional helper
programs or Perl module may need to be installed to use SWISH::Filter to filter
documents.  For example, to filter PDF documents you must install the Xpdf
package.

The filters are automatically loaded when C<SWISH::Filters-E<gt>new()> is
called.  Filters define a type and priority that determines the processing
order of the filter.  Filters are processed in this sort order until a filter
accepts the document for filtering. The filter uses the document's content type
to determine if the filter should handle the current document.  The
content-type is determined by the files suffix if not supplied by the calling
program.

The individual filters are not designed to be used as separate modules.  All
access to the filters is through this SWISH::Filter module.

Normally, once a document is filtered processing stops.  Filters can filter the
document and then set a flag saying that filtering should continue (for example
a filter that uncompresses a MS Word document before passing on to the filter
that converts from MS Word to text).  All this should be transparent to the end
user.  So, filters can be pipe-lined.

The idea of SWISH::Filter is that new filters can be created, and then
downloaded and installed to provide new filtering capabilities.  For example,
if you needed to index MS Excel documents you might be able to download a
filter from the Swish-e site and magically next time you run indexing MS Excel
docs would be indexed.

The SWISH::Filter setup can be used with -S prog or -S http.  It works best
with the -S prog method because the filter modules only need to be loaded and
compiled one time.  The -S prog program F<spider.pl> will automatically use
SWISH::Filter when spidering with default settings (using "default" as the
first parameter to spider.pl).

The -S http indexing method uses a Perl helper script called F<swishspider>.
F<swishspider> has been updated to work with SWISH::Filter, but (unlike
spider.pl) does not contain a "use lib" line to point to the location of
SWISH::Filter.  This means that by default F<swishspider> will B<not> use
SWISH::Filter for filtering.  The reason for this is because F<swishspider>
runs for every URL fetched, and loading the Filters for each document can be
slow.  The recommended way of spidering is using -S prog with spider.pl, but if
-S http is desired the way to enable SWISH::Filter is to set PERL5LIB before
running swish so that F<swishspider> will be able to locate the SWISH::Filter
module.  Here's one way to set the PERL5LIB with the bash shell:

  $ export PERL5LIB=`swish-filter-test -path`



=head1 METHODS

=over 4

=item $filter = SWISH::Filter-E<gt>new()

This creates a SWISH::Filter object.  You may pass in options as a list or a hash reference.

=back

=head2 SWISH::Filter-E<gt>new Options

There is currently only one option that can be passed in to new():

=over 4

=item ignore_filters

Pass in a reference to a list of filter names to ignore.  For example, if you have two filters installed
"Pdf2HTML" and "Pdf2XML" and want to avoid using "Pdf2XML":

    my $filter = SWISH::Filter->new( ignore_filters => ['Pdf2XML'];


=cut

sub new {
    my $class = shift;
    $class = ref( $class ) || $class;

    my %attr = ref $_[0] ? %{$_[0]} : @_ if @_;

    my $self = bless {}, $class;

    $self->{skip_filters} = {};

    $self->ignore_filters( delete $attr{ignore_filters} ) if $attr{ignore_filters};

    warn "Unknown SWISH::Filter->new() config setting '$_'\n"
        for keys %attr;

    $self->create_filter_list( %attr );

    eval { require MIME::Types };
    if ( $@ ) {
        $class->mywarn( "Failed to load MIME::Types\n$@\nInstall MIME::Types for more complete MIME support");

        # handle the lookup for a small number of types locally
        $self->{mimetypes} = $self;

    } else {
        $self->{mimetypes} = MIME::Types->new;
    }


    return $self;
}



# Here's some common mime types
my %mime_types = (
    doc   => 'application/msword',
    pdf   => 'application/pdf',
    html  => 'text/html',
    htm   => 'text/html',
    txt   => 'text/plain',
    text  => 'text/plain',
    xml   => 'text/xml',
    mp3   => 'audio/mpeg',
);

sub mimeTypeOf {
    my ( $self, $file ) = @_;
    $file =~ s/.*\.//;
    return $mime_types{$file} || undef;
}



sub ignore_filters {
    my ( $self, $filters ) = @_;

    unless ( $filters ) {
        return unless $self->{ignore_filter_list};
        return @{$self->{ignore_filter_list}};
    }

    @{$self->{ignore_filter_list}} = @$filters;


    # create lookup hash for filters to skip
    $self->{skip_filters} = map { $_, 1 } @$filters;
}



=item $doc_object = $filter-E<gt>convert();

This method filters a document.  Returns an object of the class SWISH::Filter::document
or undefined if passed in an empty document, a filename that cannot be read off disk, or
if no filters have been loaded.

SWISH::Filter::document methods listed below can be called on the object to, for
example, check if the document was filtered and to fetch the document content (filtered or
not).

You must pass in a hash (or hash reference) of parameters to the convert() method.  The
possible parameters are:

=over 8

=item document

This can be either a path to a file, or a scalar reference to a document in memory.
This is required.

=item content_type

The MIME type of the document.  This is only required when passing in a scalar
reference to a document. The content type string is what the filters use to
match a document type.

When passing in a file name and C<content_type> is not set, then the content type will
be determined from the file's extension by using the MIME::Types Perl module (available on CPAN).

=item name

Optional name to pass in to filters that will be used in error and warning messages.

=item user_data

Optional data structure that all filters may access.
This can be fetched in a filter by:

    my $user_data = $doc_object->user_data;

And used in the filter as:

    if ( ref $user_data && $user_data->{pdf2html}{title} ) {
       ...
    }

It's up to the filter author to use a unique first-level hash key for a given filter.


=back

Example of using the convert() method:

    $doc_object = $filter->convert(
        document     => $doc_ref,
        content-type => 'application/pdf',
    );

=cut


sub convert {
    my $self = shift;
    my %attr = ref $_[0] ? %{$_[0]} : @_ if @_;

    # Any filters?
    return unless $self->filter_list;


    my $doc = delete $attr{document} || die "Failed to supply document attribute 'document' when calling filter()\n";

    my $content_type = delete $attr{content_type};


    # Allow a reference to a file name (where is this used??)

    if ( ref $content_type ) {
        my $type = $self->decode_content_type( $$content_type );

        unless ( $type ) {
            warn "Failed to set content type for file reference '$$content_type'\n";
            return;
        }
        $content_type = $type;
    }



    if ( ref $doc ) {
        die "Must supply a content type when passing in a reference to a document\n"
            unless $content_type;
    } else {
        $content_type ||= $self->decode_content_type( $doc );
        unless ( $content_type ) {
            warn "Failed to set content type for document '$doc'\n";
            return;
        }

        $attr{name} ||= $doc;  # Set default name of document
    }


    $self->mywarn("\n>> Starting to process new document: $content_type");

    ## Create a new document object

    my $doc_object = SWISH::Filter::document->new( $doc, $content_type );
    return unless $doc_object;  # fails on empty doc or doc not readable

    local $SIG{__DIE__};
    local $SIG{__WARN__};


    # Look for left over config settings that we do not know about

    for my $setting ( keys %extra_methods ) {
        next unless $attr{$setting};
        my $method = "set_" . $setting;
        $doc_object->$method(delete $attr{$setting});


        # if given a document name then use that in error messages

        if ( $setting eq 'name' ) {
            $SIG{__DIE__} = sub { die "$$ Error- ", $doc_object->name, ": ", @_ };
            $SIG{__WARN__} = sub { warn "$$ Warning - ", $doc_object->name, ": ", @_ };
        }
    }

    warn "Unknown filter config setting '$_'\n"
        for keys %attr;


    # Now run through the filters


    my $done;
    for my $filter ( $self->filter_list )  {

        $self->mywarn(" ++Checking filter [$filter] for $content_type" );

        # can this filter handle this content type?
        next unless $filter->can_filter_mimetype( $doc_object->content_type );


        my $start_content_type = $doc_object->content_type;
        my $filtered_doc;

        # run the filter
        eval {
            local $SIG{__DIE__};
            $filtered_doc = $filter->filter($doc_object);
        };

        if ( $@ ) {
            $self->mywarn("Problems with filter '$filter'.  Filter disabled:\n -> $@");
            $self->filter_list( [ grep { $_ != $filter } $self->filter_list ] );
            next;
        }

        $self->mywarn(" ++ $content_type " . ($filtered_doc ? '*WAS*' : 'was not') . " filtered by $filter\n");

        # save the working filters in this list

        if ( $filtered_doc ) {  # either a file name or a reference to the doc

            # Track chain of filters

            push @{$doc_object->{filters_used}}, {
                name => $filter,
                start_content_type => $start_content_type,
                end_content_type   => $doc_object->content_type,
            };


            $doc_object->cur_doc($filtered_doc);    # and save it (filename or reference)

            # All done?
            last unless $doc_object->continue( 0 );
        }
    }


    $doc_object->dump_filters_used  if $ENV{FILTER_DEBUG};

    return $doc_object;

}





=item $filter-E<gt>mywarn()

Internal function used for writing warning messages to STDERR if
$ENV{FILTER_DEBUG} is set.  Set the environment variable FILTER_DEBUG before
running to see extra messages while processing.

=cut

sub mywarn {
    my $self = shift;

    print STDERR @_,"\n" if $ENV{FILTER_DEBUG};
}

=item @filters = $filter-E<gt>filter_list;

Returns a list of filter objects installed.

=cut

sub filter_list {
    my ( $self, $filter_ref ) = @_;

    unless ( $filter_ref ) {
        return ref $self->{filters} ? @{ $self->{filters} } : ();
    }

    $self->{filters} = $filter_ref;
}



# Creates the list of filters

sub create_filter_list {
    my ( $self, %attr ) = @_;

    my @filters;

    # Look for filters to load
    for my $inc_path ( @INC ) {
        my $cur_path = "$inc_path/SWISH/Filters";

        next unless opendir( DIR, $cur_path );


        while ( my $file = readdir( DIR ) ) {
            my $full_path = "$cur_path/$file";

            next unless -f $full_path;

            my ($base,$path,$suffix) = fileparse( $full_path,"\.pm");

            next unless $suffix eq '.pm';

            # Should this filter be skipped?
            next if $self->{skip_filters}{$base};

            $self->mywarn("\n>> Loading filter: [SWISH/Filters/${base}$suffix]");

            eval { require "SWISH/Filters/${base}$suffix" };

            if ( $@ ) {
                if ( $ENV{FILTER_DEBUG} ) {
                    print STDERR "Failed to load 'SWISH/Filters/${base}$suffix'\n",
                    '-+' x 40, "\n",
                    $@,
                    '-+' x 40, "\n";
                }
                next;
            }

            my $package =  "SWISH::Filters::" . $base;

            # Provide a base class for each filter
            {
                no strict 'refs';
                push @{"$package\::ISA"}, 'SWISH::Filters::_BASE';
            }

            my $filter = $package->new( %attr );

            $self->mywarn(":-( Filter [SWISH/Filters/${base}$suffix] not loaded\n")
                unless $filter;

            next unless $filter;  # may not get installed



            push @filters, $filter;  # save it in our list.
        }
    }

    unless ( @filters ) {
        warn "No SWISH filters found\n";
        return;
    }


    # Now sort the filters in order.
    $self->filter_list( [ sort { $a->type <=> $b->type || $a->priority <=> $b->priority } @filters ] );
}

=item @filter = $filter-E<gt>can_filter( $content_type );

This is useful for testing to see if a mimetype might be handled by SWISH::Filter
wihtout having to pass in a document.  Helpful if doing HEAD requests.

Returns an array of filters that can handle this type of document

=back

=cut

sub can_filter {
    my ( $self, $content_type ) = @_;

    my @filters;


    unless ( $content_type ) {
        warn "Failed to pass in a content type to can_filter() method";
        return;
    }

    for my $filter ( $self->filter_list ) {
        push @filters, $filter if $filter->can_filter_mimetype( $content_type );
    }

    return @filters;
}


#------------------------------------------------------
# converts a file name to a mimetype

sub decode_content_type {
    my ( $self, $file ) = @_;

    return unless $file;

    return ($self->{mimetypes})->mimeTypeOf($file);
}


=head1 WRITING FILTERS

Filters are standard perl modules that are installed into the SWISH::Filters name space.
Filters are not complicated -- see the existing filters for examples.

Each filter defines the content-types (or mimetypes) that it can handle.  These
are specified as a list of regular expressions to match against the document's
content-type.  If one of the mimetypes of a filter match the incoming
document's content-type the filter is called.  The filter can then either
filter the content or return undefined indicating that it decided not to
filter the document for some reason.  If the document is converted the filter
returns either a reference to a scalar of the content or a file name where the
content is stored.  The filter also must change the content-type of the document
to reflect the new document.

Filters typically use external programs or modules to do that actual work of
converting a document from one type to another.  For example, programs in the
Xpdf packages are used for converting PDF files.  The filter can (and should)
test for those programs in its new() method.

Filters also can define a type and priority.  These attributes are used
to set the order filters are tested for a content-type match.  This allows
you to have more than one filter that can work on the same content-type.

If a filter calls die() then the filter is removed from the chain and will not be
called again I<during the same run>.  Calling die when running with -S http or
-S fs has no effect since the program is run once per document.

Once a filter returns something other than undef no more filters will be
called.  If the filter calls $filter-E<gt>set_continue then processing will
continue as if the file was not filtered.  For example, a filter can uncompress
data and then set $filter-E<gt>set_continue and let other filters process the
document.


This is the list of methods the filter should or may define (as specificed):

=over 4

=item new()  * required *

This method returns either an object which provides access to the filter, or undefined
if the filter is not to be used.

The new() method is a good place to check for required modules or helper programs.
Returning undefined prevents the filter from being included in the filter chain.

The new method must return a blessed hash reference.  The only required attribute
is B<mimetypes>.  This attribute must contain a reference to an array of regular
expressions used for matching the content-type of the document passed in.

Example:

    sub new {
        my ( $class ) = @_;

        # List of regular expressions
        my @mimetypes = (
            qr[application/(x-)?msword],
            qr[application/worddoc],
        );

        my %settings = (
            mimetypes   => \@mimetypes,

            # Optional settings
            priority    => 20,
            type        => 2,
        );

        return bless \%settings, $class;
    }

The attribute "mimetypes" returns an array reference to a list of regular
expressions.  Those patterns are matched against each document's content type.

=item filter() * required *

This is the function that does the work of converting a document from one content type
to another.  The function is passed the document object.  See document object methods
listed below for what methods may be called on a document.

The function can return undefined (or any false value) to indicate that the
filter did not want to process the document.  Other filters will then be tested for
a content type match.

If the document is filtered then the filter must set the new document's content
type (if it changed) and return either a file name where the document can be found or
a reference to a scalar containing the document.

=item type()

Returns a number. Filters are sorted (for processing in a specific order)
and this number is simply the primary key used in sorting.  If not specified
the filter's type used for sorting is 2.

This is an optional method.  You can also set the type in your new() constructor
as shown above.


=item priority()

Returns a number.  Filters are sorted (for processing in a specific order)
and this number is simply the secondary key used in sorting.  If not specified
the filter's priority is 50.

This is an optional method.  You can also set the priority in your new() constructor
as shown above.


=back

Again, the point of the type() and priority() methods is to allow setting the sort order
of the filters.  Useful if you have two filters for filtering the same content-type,
but prefer to use one over the other.  Neither are required.

Here's a module to convert MS Word documents using the program "catdoc":

    package SWISH::Filters::Doc2txt;
    use vars qw/ $VERSION /;

    $VERSION = '0.02';


    sub new {
        my ( $class ) = @_;

        my $self = bless {
            mimetypes   => [ qr!application/(x-)?msword! ],
            priority    => 50,
        }, $class;


        # check for helpers
        return $self->set_programs( 'catdoc' );

    }


    sub filter {
        my ( $self, $doc ) = @_;

        my $content = $self->run_catdoc( $doc->fetch_filename ) || return;

        # update the document's content type
        $filter->set_content_type( 'text/plain' );

        # return the document
        return \$content;
    }
    1;

The new() constructor creates a blessed hash which contains an array reference
of mimetypes patterns that this filter accepts.  The priority sets this
filter to run after any other filters that might handle the same type of content.
The F<set_programs()> function says that we need to call a program called "catdoc".
The function either returns $self or undefined if catdoc could not be found.
The F<set_programs()> function creates a new method for running catdoc.

The filter function runs catdoc passing in the name of the file (if the file is in memory
a temporary file is created).  That F<run_catdoc()> function was created by the
F<set_programs()> call above.


=cut


#=========================================================================
package SWISH::Filter::document;
use strict;
use File::Temp;
use Symbol;

use vars '$AUTOLOAD';

=head1 SWISH::Filter::document Methods

These methods are available to Filter authors, and also provide access to the
document after calling the convert() method to end-users of SWISH::Filter.

End users of SWISH::Filter will use a subset of these methods.  Mostly:

   $doc_object->fetch_doc      # and alias for fetch_document_reference()
   $doc_object->was_filtered   # true the document was filtered
   $doc_object->content_type   # document's current content type (mime type)
   $doc_object->swish_parser_type # returns a parser type to use with Swish-e -S prog method
   $doc_object->is_binary      # returns $content_type !~ m[^text/];

These methods are also available to the individual filter modules.  The filter's "filter"
function is also passed a SWISH::Filter::document object.  Method calls may be made on this
object to check the document's current content type, or to fetch the document as either a
file name or a reference to a scalar containing the document content.

=cut

# Returns a new SWISH::Filter::document object
# or null if just can't process the document

sub new {
    my ( $class, $doc, $content_type ) = @_;

    return unless $doc && $content_type;

    my $self = bless {}, $class;

    if ( ref $doc ) {
        unless ( length $$doc ) {
            warn "Empty document passed to filter\n";
            return;
        }

        die "Must supply a content type when passing in a reference to a document\n"
            unless $content_type;


    } else {

        unless ( -r $doc ) {
            warn "Filter unable to read doc '$doc': $!\n";
            return;
        }
    }

    $self->set_content_type( $content_type );

    $self->{cur_doc} = $doc;

    return $self;
}

# Clean up any temporary files

sub DESTROY {
    my $self = shift;
    $self->remove_temp_file;
}


sub cur_doc {
    my ( $self, $doc_ref ) = @_;
    $self->{cur_doc} = $doc_ref if $doc_ref;
    return $self->{cur_doc};
}

sub remove_temp_file {
    my $self = shift;

    unlink delete $self->{temp_file} if $self->{temp_file};
}

# Used for tracking what filter(s) were used in processing

sub filters_used {
    my $self = shift;
    return $self->{filters_used} || undef;
}

sub dump_filters_used {
    my $self = shift;
    my $used = $self->filters_used;

    local $SIG{__WARN__};
    warn "\nFinal Content type for ", $self->name, " is ", $self->content_type, "\n";

    unless ( $used ) {
        warn "  *No filters were used\n";
        return;
    }

    warn "  >Filter $_->{name} converted from [$_->{start_content_type}] to [$_->{end_content_type}]\n"
        for @$used;
}

=head2 Methods used by end-users and filter authors

=over 4


=item $doc_ref = $doc_object-E<gt>fetch_doc_reference;

Returns a scalar reference to the document.  This can be used when the filter
can operate on the document in memory (or if an external program expects the input
to be from standard input).

If the file is currently on disk then it will be read into memory.  If the file was stored
in a temporary file on disk the file will be deleted once read into memory.
The file will be read in binmode if $doc-E<gt>is_binary is true.

Note that $doc_object-E<gt>fetch_doc is an alias.

=cut

sub fetch_doc_reference {
    my ( $self ) = @_;

    return ref $self->{cur_doc}  # just $self->read_file should work
        ? $self->{cur_doc}
        : $self->read_file;
}

# here's an alias for fetching a document reference.

*fetch_doc = *fetch_doc_reference;


=item $was_filtered = $doc_object-E<gt>was_filtered

Returns true if some filter processed the document

=cut

sub was_filtered {
    my $self = shift;
    return $self->filters_used ? 1 : 0;
}

=item $content_type = $doc_object-E<gt>content_type;

Fetches the current content type for the document.

Example:

    return unless $filter->content_type =~ m!application/pdf!;


=cut

sub content_type {
    return $_[0]->{content_type} || '';
}

=item $type = $doc_object-E<gt>swish_parser_type

Returns a parser type based on the content type

=cut

# Map content types to swish-e parsers.

my %swish_parser_types = (
    'text/html'     => 'HTML*',
    'text/xml'      => 'XML*',
    'text/plain'    => 'TXT*',
);


sub swish_parser_type {
    my $self = shift;

    my $content_type = $self->content_type || return;

    for ( keys %swish_parser_types ) {
        return $swish_parser_types{$_} if
            $content_type =~ /^\Q$_/;
    }

    return;
}

=item $doc_object-E<gt>is_binary

Returns true if the document's content-type does not match "text/".

=back

=cut

sub is_binary {
    my $self = shift;
    return $self->content_type !~ m[^text];
}

=head2 Methods used by filter authors

=over 4

=item $file_name = $doc_object-E<gt>fetch_filename;

Returns a path to the document as stored on disk.
This name can be passed to external programs (e.g. catdoc) that expect input
as a file name.

If the document is currently in memory then a temporary file will be created.  Do not expect
the file name passed to be the real path of the document.

The file will be written in binmode if $doc-E<gt>is_binary is true.

This method is not normally used by end-users of SWISH::Filter.

=cut


# This will create a tempoary file if file is in memory

sub fetch_filename {
    my ( $self ) = @_;

    return ref $self->{cur_doc}
        ? $self->create_temp_file
        : $self->{cur_doc};
}

=item $doc_object-E<gt>set_continue;

Processing will continue to the next filter if this is set to a true value.
This should be set for filters that change encodings or uncompress documents.

=cut

sub set_continue {
    my ( $self ) = @_;
    return $self->continue(1);
}

sub continue {
    my ( $self, $continue ) = @_;
    my $old = $self->{continue} || 0;
    $self->{continue}++ if $continue;
    return $old;
}



=item $doc_object-E<gt>set_content_type( $type );

Sets the content type for a document.

=cut

sub set_content_type {
    my ( $self, $type ) = @_;
    die "Failed to pass in new content type\n" unless $type;
    $self->{content_type} = $type;
}


sub read_file {
    my $self = shift;
    my $doc = $self->{cur_doc};
    return $doc if ref $doc;

    my $sym = gensym();
    open($sym, "<$doc" ) or die "Failed to open file '$doc': $!";
    binmode $sym if $self->is_binary;
    local $/ = undef;
    my $content = <$sym>;
    close $sym;
    $self->{cur_doc} = \$content;

    # Remove the temporary file, if one was created.
    $self->remove_temp_file;


    return $self->{cur_doc};
}


# write file out to a temporary file

sub create_temp_file {
    my $self = shift;
    my $doc = $self->{cur_doc};

    return $doc unless ref $doc;

    my ( $fh, $file_name ) = File::Temp::tempfile();

    # assume binmode if we need to filter...
    binmode $fh if $self->is_binary;

    print $fh $$doc or die "Failed to write to '$file_name': $!";
    close $fh or die "Failed to close '$file_name' $!";

    $self->{cur_doc} = $file_name;
    $self->{temp_file} = $file_name;

    return $file_name;
}


=item $doc_object-E<gt>name

Fetches the name of the current file.  This is useful for printing out the
name of the file in an error message.
This is the name passed in to the SWISH::Filter-E<gt>convert method.
It is optional and thus may not always be set.

    my $name = $doc_object->name || 'Unknown name';
    warn "File '$name': failed to convert -- file may be corrupt\n";


=item $doc_object-E<gt>user_data

Fetches the the user_data passed in to the filter.
This can be any data or data structure passed into SWISH::Filter-E<gt>new.

This is an easy way to pass special parameters into your filters.

Example:

    my $data = $doc_object->user_data;
    # see if a choice for the <title> was passed in
    if ( ref $data eq 'HASH' && $data->{pdf2html}{title_field}  {
       ...
       ...
    }

=back

=cut

sub AUTOLOAD {
    my ( $self, $newval ) = @_;
    no strict 'refs';


    if ($AUTOLOAD =~ /.*::set_(\w+)/ && $SWISH::Filter::extra_methods{$1})
    {
       my $attr_name=$1;
       *{$AUTOLOAD} = sub { $_[0]->{$attr_name} = $_[1]; return };
       return $self->{$attr_name} = $newval;
    }

    elsif ($AUTOLOAD =~ /.*::(\w+)/ && $SWISH::Filter::extra_methods{$1})
    {
       my $attr_name=$1;
       *{$AUTOLOAD} = sub { return $_[0]->{$attr_name} };
       return $self->{$attr_name};
    }

    die "No such method: $AUTOLOAD\n";
}



#======================================================================================
# Default methods for the filters
package SWISH::Filters::_BASE;
use strict;


=head1 SWISH::Filters::_BASE

Each filter is a subclass of SWISH::Filters::_BASE.  A number of methods
are available by default (and some can be overridden).  Others are useful
when writing your new() constructor.

=over 4

=item $self-E<gt>type

This method fetches the type of the filter.  The value returned sets the
primary sort key for sorting the filters.  You can override this in your
filter, or just set it as an attribute in your object.  The default is 2.

The idea of the "type" is to create groups of filters, if needed.
For example, you might have a set of filters that are used for uncompressing
some documents before passing on to another group for filtering.

=cut

sub type { 2 };

=item $self-E<gt>priority

This method fetches the priority of the filter.  The value returned sets the
secondary sort key for sorting the filters.  You can override this in your
filter, or just set it as an attribute in your object.  The default method
returns 50.

The priority is useful if you have multiple filters for the same content type that
use different methods for filtering (say one uses wvWare and another uses catdoc for
filtering MS Word files).  You might give the wvWare filter a lower priority number
so it runs before the catdoc filter if both wvWare AND catdoc happen to be installed
at the same time.

=cut

sub priority { 50 };  # default priority

=item @types = $self-E<gt>mimetypes

Returns the list of mimetypes (as regular expressions) set for the filter.

=cut


sub mimetypes {
    my $self = shift;
    die "Filter [$self] failed to set 'mimetypes' in new() constructor\n"
        if ! $self->{mimetypes};

    die "Filter [$self] 'mimetypes' entry is not an array reference\n"
        unless ref $self->{mimetypes} eq 'ARRAY';

    return @{ $self->{mimetypes} };
}

=item $pattern = $self-E<gt>can_filter_mimetype( $content_type )

Returns true if passed in content type matches one of the filter's mimetypes
Returns the pattern that matched.

=cut

sub can_filter_mimetype {
    my ( $self, $content_type ) = @_;

    die "Must supply content_type to can_filter_mimetype()" unless $content_type;
    for my $pattern ( $self->mimetypes ) {
        return $pattern if $content_type =~ /$pattern/;
    }
    return;
}

=item mywarn( $message )

method for printing out message if debugging is available

=cut

sub mywarn {
    my $self = shift;

    print STDERR "Filter: $self: ", @_,"\n" if $ENV{FILTER_DEBUG};
}

=item $boolean = $self-E<gt>set_programs( @program_list );

Returns true if all the programs listed in @program_list are found
and can be executed as the current user.  Creates a method for each
program with the "run_" prefix.  Returns false is ANY program cannot
be found.

Actually, it returns $self, so you can make it the last statement in
your constructor.

So in your constructor you might do:

    return $self->set_programs( qw/ pdftotext pdfinfo / );

Then in your filter() method:

    my $content = $self->run_pdfinfo( $doc->fetch_filename, [options] );

=cut

sub set_programs {
    my ($self, @progs ) = @_;

    for my $prog ( @progs ) {
        my $path = $self->find_binary( $prog );
        unless ( $path ) {
            $self->mywarn("Can not use Filter: failed to find $prog.  Maybe need to install?");
            return;
        }

        no strict 'refs';
        *{"run_$prog"} = sub { 
            my $self = shift;
            return $self->run_program( $path, @_ ); # closure
        };
    }

    return $self;
}


=item $path = $self-E<gt>find_binary( $prog );

Use in a filter's new() method to test for a necesary program located in $PATH.
Returns the path to the program or undefined if not found or does not pass the -x
file test.

=cut

use Config;
my @path_segments;

sub find_binary {
    my ( $self, $prog ) = @_;

    unless ( @path_segments ) {
        my $path_sep = $Config{path_sep} || ':';

        @path_segments = split /\Q$path_sep/, $ENV{PATH};

        if ( my $libexecdir = get_libexec() ) {
            push @path_segments, $libexecdir;
        }
    }

    $self->mywarn("Find path of [$prog] in " . join ':', @path_segments);


    for ( @path_segments ) {
        my $path = "$_/$prog";

        # For buggy Windows98 that accepts forward slashes if the filename isn't too long
        $path =~ s[/][\\]g if $^O =~ /Win32/;

        if ( -x $path ) {

            $self->mywarn(" * Found program at: [$path]\n");
            return $path;
        }
        $self->mywarn("  Not found at path [$path]" );


        # ok, try Windows extenstions
        if ( $^O =~ /Win32/ ) {
            for my $extension ( qw/ exe bat / ) {
                if ( -x "$path.$extension" ) {
                    $self->mywarn(" * Found program at: [$path.$extension]\n");
                    return "$path.$extension";
                }
                $self->mywarn("  Not found at path [$path.$extension]" );
            }
        }

    }
    return;
}

# Try and return libexecdir in case programs are installed there (the case with Windows)
# Assumes that we are running from libexecdir or bindir
# The other option under Windows would be to fetch libexecdir from the Windows registry,
# but that could break if a new (another) swish install was done since the registry
# would then point to the new install location.

sub get_libexec {

   return 'c:/swish-e/lib/swish-e';  # the below isn't robust, so set at install time

   return unless $FindBin::Bin;

   # Look for something we expect in libexecdir.

   # Are we in $libexecdir already (like with swishspider or spider.pl)
   return $FindBin::Bin if -e "$FindBin::Bin/spider.pl";

   # Are we in $prefix/bin? (swish-filter-test)
   return "$FindBin::Bin/../lib/swish-e" if -e "$FindBin::Bin/../lib/swish-e/spider.pl";


   return;


}

=item $bool = $self-E<gt>use_modules( @module_list );

Attempts to load each of the module listed and calls its import() method.

Use to test and load required modules within a filter without aborting.

    return unless $self->use_modules( qw/ Spreadsheet::ParseExcel  HTML::Entities / );

A warning message is displayed if the FILTER_DEBUG environment variable is true.
Returns $self if no error.


=cut

sub use_modules {
    my ( $self, @modules ) = @_;

    for my $mod ( @modules ) {
        $self->mywarn("trying to load [$mod]");

        eval { eval "require $mod" or die "$!\n" };

        if ( $@ ) {
            my $caller = caller();
            $self->mywarn("Can not use Filter $caller -- need to install $mod: $@");
            return;
        }

        $self->mywarn(" ** Loaded $mod **");

        # Export back to caller
        $mod->export_to_level( 1 ) if $mod->can('export_to_level');
    }
    return $self;
}

=item $doc_ref = $self-E<gt>run_program( $program, @args );

Runs $program with @args.  Must pass in @args.

Under Windows calls IPC::Open2, which may pass data through the shell.  Double-quotes are
escaped (backslashed) and each parameter is wrapped in double-quotes.

On other platforms a fork and exec is used to avoid passing any data through the shell.
Returns a reference to a scalar containing the output from your program, or dies.

This method is intended to read output from a program that converts one format into text.
The output is read back in text mode -- on systems like Windows this means \r\n (CRLF) will
be convertet to \n.

=cut

sub run_program {
    my $self = shift;

    die "No arguments passed to run_program()\n"
        unless @_;

    die "Must pass arguments to program '$_[0]'\n"
        unless @_ > 1;

    my $fh = $^O =~ /Win32/i || $^O =~ /VMS/i
         ? $self->windows_fork( @_ )
         : $self->real_fork( @_ );

    local $/ = undef;
    my $output = <$fh>;
    close $fh;

    # When using IPC::Open3 need to reap the processes.
    waitpid delete $self->{pid}, 0 if $self->{pid};

    return $output;
}


#==================================================================
# Run swish-e by forking
#

use Symbol;

sub real_fork {
    my ( $self, @args ) = @_;


    # Run swish
    my $fh = gensym;
    my $pid = open( $fh, '-|' );

    die "Failed to fork: $!\n" unless defined $pid;

    return $fh if $pid;

    delete $self->{temp_file};  # in child, so don't want to delete on destroy.

    exec @args or exit;  # die "Failed to exec '$args[0]': $!\n";
}


#=====================================================================================
# Need
#
sub windows_fork {
    my ( $self, @args ) = @_;


    require IPC::Open2;
    my ( $rdrfh, $wtrfh );

    my @command = map { s/"/\\"/g; qq["$_"] }  @args;


    my $pid = IPC::Open2::open2($rdrfh, $wtrfh, @command );

    # IPC::Open3 uses binmode for some reason (5.6.1)
    # Assume that the output from the program will be in text
    # Maybe an invalid assumption if running through a binary filter

    binmode $rdrfh, ':crlf';  # perhpaps: unless delete $self->{binary_output};

    $self->{pid} = $pid;

    return $rdrfh;
}


=back

=cut

1;
__END__


=head1 TESTING

Filters can be tested with the F<swish-filter-test> program.  Run:

   swish-filter-test -man

for documentation.

=head1 SUPPORT

Please contact the Swish-e discussion list.  http://swish-e.org

=head1 Bugs, todo items, and other notes

TBD


=head1 AUTHOR

Bill Moseley

=head1 COPYRIGHT

This library is free software; you can redistribute it
and/or modify it under the same terms as Perl itself.


=cut
