###########################################################################
#
# ConvertToPlug.pm -- plugin that inherits from BasPlug
#
# 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.
#
###########################################################################

# This plugin is inherited by such plugins as WordPlug, PPTPlug, PSPlug, 
# RTFPlug and PDFPlug. It facilitates the conversion of these document types 
# to either HTML, TEXT or a series of images. It works by dynamically loading 
# an appropriate secondary plugin (HTMLPlug, StructuredHTMLPlug, 
# PagedImgPlug or TEXTPlug) based on the plugin argument 'convert_to'. 

package ConvertToPlug;

use BasPlug;
use ghtml;
use HTMLPlug;
use TEXTPlug;
use PagedImgPlug;

use strict;
no strict 'refs'; # allow filehandles to be variables and viceversa
no strict 'subs';
sub BEGIN {
    @ConvertToPlug::ISA = ('BasPlug');
}

my $convert_to_list =
    [ {	'name' => "auto",
	'desc' => "{ConvertToPlug.convert_to.auto}" },
      {	'name' => "html",
	'desc' => "{ConvertToPlug.convert_to.html}" },
      {	'name' => "text",
	'desc' => "{ConvertToPlug.convert_to.text}" }
      ];

my $arguments =
    [ { 'name' => "convert_to",
	'desc' => "{ConvertToPlug.convert_to}",
	'type' => "enum",
	'reqd' => "yes",
	'list' => $convert_to_list, 
	'deft' => "auto" },
      { 'name' => "keep_original_filename",
	'desc' => "{ConvertToPlug.keep_original_filename}",
	'type' => "flag" },
      { 'name' => "title_sub",
	'desc' => "{HTMLPlug.title_sub}",
	'type' => "string", 
	#'type' => "regexp",
	'deft' => "" },
      { 'name' => "apply_fribidi",
	'desc' => "{ConvertToPlug.apply_fribidi}",
	'type' => "flag",
	'reqd' => "no" },
      { 'name' => "use_strings",
	'desc' => "{ConvertToPlug.use_strings}",
	'type' => "flag",
	'reqd' => "no" },
      { 'name' => "extract_keyphrases",
	'desc' => "{BasPlug.extract_keyphrases}",
	'type' => "flag",
	'reqd' => "no",
	'hiddengli' => "yes" },
      { 'name' => "extract_keyphrase_options",
	'desc' => "{BasPlug.extract_keyphrase_options}",
	'type' => "string",
	'reqd' => "no",
	'hiddengli' => "yes" } ];

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


sub load_secondary_plugins
{
    my $self = shift (@_);
    my ($class,$input_args,$hashArgOptLists) = @_;

    my @convert_to_list = split(",",$self->{'convert_to'});
    my $secondary_plugins = {};
    # find the plugin

    foreach my $convert_to (@convert_to_list) {
	# load in "convert_to" plugin package
	my $plugin_class = $convert_to."Plug";
	my $plugin_package = $plugin_class.".pm";

	my $colplugname = &util::filename_cat($ENV{'GSDLCOLLECTDIR'},
					      "perllib/plugins", 
					      $plugin_package);
	my $mainplugname = &util::filename_cat($ENV{'GSDLHOME'},
					       "perllib/plugins", 
					       $plugin_package);

	if (-e $colplugname) {require $colplugname;}
	elsif (-e $mainplugname) { require $mainplugname; }
	else {
	    &gsprintf(STDERR, "{plugin.could_not_find_plugin}\n",
		      $plugin_class);
	    die "\n";
	}

	# call its constructor with extra options that we've worked out!
	my $arglist = $input_args->{$plugin_class};

	my ($secondary_plugin);
	eval("\$secondary_plugin = new $plugin_class([],\$arglist)");
	die "$@" if $@;
	$secondary_plugins->{$plugin_class} = $secondary_plugin;
    }
    $self->{'secondary_plugins'} = $secondary_plugins;
}

sub new {
    my ($class) = shift (@_);
    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
    push(@$pluginlist, $class);
    my $classPluginName = (defined $pluginlist->[0]) ? $pluginlist->[0] : $class;
    if(defined $arguments){ push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});}
    if(defined $options) { push(@{$hashArgOptLists->{"OptList"}},$options)};

    my $self = new BasPlug($pluginlist, $inputargs, $hashArgOptLists);
    
    if ($self->{'info_only'}) {
	# don't worry about any options etc
	return bless $self, $class;
    }

    my $convert_to_type = $self->{'convert_to'};
    if (!defined $convert_to_type || $convert_to_type eq "") {
	$convert_to_type = "auto";
    }
    my $windows_scripting = $self->{'windows_scripting'};
    $windows_scripting = 0 unless defined $windows_scripting;
    if ($classPluginName eq "PDFPlug") {
	if ($convert_to_type eq "text" && 
	    $ENV{'GSDLOS'} =~ /^windows$/i) {
	    print STDERR "Windows does not support pdf to text. PDFs will be converted to HTML instead\n";
	    $convert_to_type = "html";
	}
    } elsif ($classPluginName eq "WordPlug") {
	if ($windows_scripting && $ENV{'GSDLOS'} =~ /^windows$/i && $convert_to_type =~ /^(html|auto)$/) {
	    # we use structured HTML, not normal html
	    $convert_to_type = "structuredhtml";
	} 
    } elsif ($classPluginName eq "PPTPlug") {
	if ($windows_scripting && $ENV{'GSDLOS'} =~ /^windows$/i && $convert_to_type eq "auto") {
	    # we use paged img
	    $convert_to_type = "pagedimg_jpg";
	} 
    } elsif ($classPluginName eq "PSPlug") {
	if ($convert_to_type eq "auto") {
	    # we use text
	    $convert_to_type = "text";
	}
    }
    
    if ($convert_to_type eq "auto") {
	# choose html for now - should choose a format based on doc type
	$convert_to_type = "html";
    }
    
    if ($convert_to_type eq "html") {
	$self->{'convert_to'} = "HTML";
	$self->{'convert_to_ext'} = "html";
    } elsif ($convert_to_type eq "text") {
	$self->{'convert_to'} = "TEXT";
	$self->{'convert_to_ext'} = "txt";
    } elsif ($convert_to_type eq "structuredhtml") {
	$self->{'convert_to'} = "StructuredHTML";
	$self->{'convert_to_ext'} = "html";
    } elsif ($convert_to_type =~ /^pagedimg/) {
	$self->{'convert_to'} = "PagedImg";
	my ($convert_to_ext) = $convert_to_type =~ /pagedimg\_(jpg|gif|png)/i;
	$convert_to_ext = 'jpg' unless defined $convert_to_ext;
	$self->{'convert_to_ext'} = $convert_to_ext;
    }

    return bless $self, $class;
}


sub init {
    my $self = shift (@_);
    my ($verbosity, $outhandle, $failhandle) = @_;

    $self->SUPER::init($verbosity,$outhandle,$failhandle);

    my $secondary_plugins =  $self->{'secondary_plugins'};

    foreach my $plug_name (keys %$secondary_plugins) {
	my $plugin = $secondary_plugins->{$plug_name};
	$plugin->init($verbosity,$outhandle,$failhandle);
    }
}

sub deinit {
    # called only once, after all plugin passes have been done

    my ($self) = @_;

    my $secondary_plugins =  $self->{'secondary_plugins'};

    foreach my $plug_name (keys %$secondary_plugins) {
	my $plugin = $secondary_plugins->{$plug_name};
	$plugin->deinit();
    }
}

sub convert_post_process
{
    # by default do no post processing
    return;
}


# Run conversion utility on the input file.  
#
# The conversion takes place in a collection specific 'tmp' directory so 
# that we don't accidentally damage the input.
#
# The desired output type is indicated by $output_ext.  This is usually
# something like "html" or "word", but can be "best" (or the empty string)
# to indicate that the conversion utility should do the best it can.
sub tmp_area_convert_file {
    my $self = shift (@_);
    my ($output_ext, $input_filename, $textref) = @_;
    
    my $outhandle = $self->{'outhandle'};
    my $convert_to = $self->{'convert_to'};
    my $failhandle = $self->{'failhandle'};
    my $convert_to_ext = $self->{'convert_to_ext'};
    
    # softlink to collection tmp dir
    my $tmp_dirname 
	= &util::filename_cat($ENV{'GSDLCOLLECTDIR'}, "tmp");
    &util::mk_dir($tmp_dirname) if (!-e $tmp_dirname);

    # derive tmp filename from input filename
    my ($tailname, $dirname, $suffix)
	= &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");

    # Remove any white space from filename -- no risk of name collision, and
    # makes later conversion by utils simpler. Leave spaces in path...
    # tidy up the filename with space, dot, hyphen between
    $tailname =~ s/\s+//g; 
    $tailname =~ s/\.+//g;
    $tailname =~ s/\-+//g;

    # convert to utf-8 otherwise we have problems with the doc.xml file
    # later on
    &unicode::ensure_utf8(\$tailname);

    $suffix = lc($suffix);
    my $tmp_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
    &util::soft_link($input_filename, $tmp_filename);
    my $verbosity = $self->{'verbosity'};
    if ($verbosity > 0) {
	print $outhandle "Converting $tailname$suffix to $convert_to format\n";
    }

    my $errlog = &util::filename_cat($tmp_dirname, "err.log");
    
    # Execute the conversion command and get the type of the result,
    # making sure the converter gives us the appropriate output type
    my $output_type="";
    if ($convert_to =~ m/PagedImg/i) {
	$output_type = lc($convert_to)."_".lc($convert_to_ext);
    } else {
	$output_type = lc($convert_to);
    }

    my $cmd = "perl -S gsConvert.pl -verbose $verbosity ";
    if (defined $self->{'convert_options'}) {
	$cmd .= $self->{'convert_options'} . " ";
    }
    if ($self->{'use_strings'}) {
      $cmd .= "-use_strings ";
    }
    $cmd .= "-errlog \"$errlog\" -output $output_type \"$tmp_filename\"";

    $output_type = `$cmd`;

    # remove symbolic link to original file
    &util::rm($tmp_filename);

    # Check STDERR here
    chomp $output_type;
    if ($output_type eq "fail") {
	print $outhandle "Could not convert $tailname$suffix to $convert_to format\n";
	print $failhandle "$tailname$suffix: " . ref($self) . " failed to convert to $convert_to\n";
	# The following  meant that if a conversion failed, the document would be counted twice - do we need it for anything?
	#$self->{'num_not_processed'} ++;
	if (-s "$errlog") {
	    open(ERRLOG, "$errlog");
	    while (<ERRLOG>) {
		print $outhandle "$_";
	    }
	    print $outhandle "\n";
	    close ERRLOG;
	}
	&util::rm("$errlog") if (-e "$errlog");
	return "";
    }

    # store the *actual* output type and return the output filename
    # it's possible we requested conversion to html, but only to text succeeded
    #$self->{'convert_to_ext'} = $output_type;
    if ($output_type =~ /html/i) {
	$self->{'converted_to'} = "HTML";
    } elsif ($output_type =~ /te?xt/i) {
	$self->{'converted_to'} = "TEXT";
    } elsif ($output_type =~ /item/i){
	$self->{'converted_to'} = "PagedImg";
    }
    
    my $output_filename = $tmp_filename;
    if ($output_type =~ /item/i) {
	# running under windows
	if ($ENV{'GSDLOS'} =~ /^windows$/i) {
	    $output_filename = $tmp_dirname . "\\$tailname\\" . $tailname . ".$output_type";
	} else {
	    $output_filename = $tmp_dirname . "\/$tailname\/" . $tailname . ".$output_type";
	}
    } else {
	$output_filename =~ s/$suffix$/.$output_type/;
    }
    
    return $output_filename;
}


# Override BasPlug read
# We don't want to get language encoding stuff until after we've converted
# our file to either TEXT or HTML or PagedImage.
sub read {
    my $self = shift (@_);
    my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;

    my $outhandle = $self->{'outhandle'};
    
    my ($block_status,$filename) = $self->read_block(@_);
    return $block_status if ((!defined $block_status) || ($block_status==0));
    $file = $self->read_tidy_file($file);
    
    my $output_ext = $self->{'convert_to_ext'};
    my $conv_filename = "";
    $conv_filename = $self->tmp_area_convert_file($output_ext, $filename);
    
    if ("$conv_filename" eq "") {return -1;} # had an error, will be passed down pipeline 
    if (! -e "$conv_filename") {return -1;} 
    $self->{'conv_filename'} = $conv_filename;
    $self->convert_post_process($conv_filename);

    # Run the "fribidi" (http://fribidi.org) Unicode Bidirectional Algorithm program over the converted file
    # Added for fixing up Persian PDFs after being processed by pdftohtml, but may be useful in other cases too
    if ($self->{'apply_fribidi'} && $self->{'converted_to'} =~ /(HTML|TEXT)/) {
	my $fribidi_command = "fribidi \"$conv_filename\" >\"${conv_filename}.tmp\"";
	if (system($fribidi_command) != 0) {
	    print STDERR "ERROR: Cannot run fribidi on \"$conv_filename\".\n";
	}
	else {
	    &util::mv("${conv_filename}.tmp", $conv_filename);
	}	
    }

    my $secondary_plugins =  $self->{'secondary_plugins'};
    my $num_secondary_plugins = scalar(keys %$secondary_plugins);

    if ($num_secondary_plugins == 0) {
	print $outhandle "Warning: No secondary plugin to use in conversion.  Skipping $file\n";
	return 0; # effectively block it
    }

    my @plugin_names = keys %$secondary_plugins;
    my $plugin_name = shift @plugin_names;
	
    if ($num_secondary_plugins > 1) {
	print $outhandle "Warning: Multiple secondary plugins not supported yet!  Choosing $plugin_name\n.";
    }
   
    my $secondary_plugin = $secondary_plugins->{$plugin_name};

    # note: metadata is not carried on to the next level
    my ($rv,$doc_obj) 
	= $secondary_plugin->read_into_doc_obj ($pluginfo,"", $conv_filename, 
						$metadata, $processor, $maxdocs, $total_count,
						$gli);

    if ((!defined $rv) || ($rv<1)) {
	# wasn't processed
	return $rv;
    }
    
    # Override previous gsdlsourcefilename set by secondary plugin
    my $collect_file = &util::filename_within_collection($filename);
    my $collect_conv_file = &util::filename_within_collection($conv_filename);
    $doc_obj->set_source_filename ($collect_file); 
    $doc_obj->set_converted_filename($collect_conv_file);

    my ($filemeta) = $file =~ /([^\\\/]+)$/;
    $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Source", &ghtml::dmsafe($filemeta));
    $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
    $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "FileSize", (-s $filename));

    if ($self->{'cover_image'}) {
	$self->associate_cover_image($doc_obj, $filename);
    }

    # do plugin specific processing of doc_obj
    unless (defined ($self->process(undef, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
	print STDERR "<ProcessingError n='$file'>\n" if ($gli);
	return -1;
    }
    # do any automatic metadata extraction
    $self->auto_extract_metadata ($doc_obj);

    # have we found a Title??
    $self->title_fallback($doc_obj,$doc_obj->get_top_section(),$filemeta);

    # add an OID
    $doc_obj->set_OID();
    # process the document
    $processor->process($doc_obj);

    $self->{'num_processed'} ++;

    return 1;
}


# do plugin specific processing of doc_obj for doc_ext type
sub process_type {
    my $self = shift (@_);
    my ($doc_ext, $base_dir, $file, $doc_obj) = @_;
    
    # associate original file with doc object
    my $cursection = $doc_obj->get_top_section();
    my $filename = &util::filename_cat($base_dir, $file);
    my $assocfilename = "doc.$doc_ext";
    if ($self->{'keep_original_filename'} == 1) {
	# this should be the same filename that was used for the Source metadata, as we will use [Source] in the srclink
	($assocfilename) = $file =~ /([^\\\/]+)$/;
    }
    $doc_obj->associate_file($filename, $assocfilename, undef, $cursection);

    my $file_type;

    if ($doc_ext eq "doc") {
    	$file_type = "Word";
    } elsif ($doc_ext eq "xls") {
	$file_type = "Excel";
    } elsif ($doc_ext eq "ppt") {
	$file_type = "PPT"; 
    } elsif ($doc_ext eq "pdf") {
	$file_type = "PDF"; 
    } elsif ($doc_ext eq "rtf") {
	$file_type = "RTF";
    } elsif ($doc_ext eq "ps") {
	$file_type = "PS";
    }

    my $file_format = $file_type || "unknown";

    # We use set instead of add here because we only want one value
    $doc_obj->set_utf8_metadata_element($cursection, "FileFormat", $file_format);
    my $doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/[archivedir]/doc.$doc_ext\">";
    if ($self->{'keep_original_filename'} == 1) {
	$doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/[archivedir]/[Source]\">";
    }
    $doc_obj->add_utf8_metadata ($cursection, "srclink",  $doclink); 
    $doc_obj->add_utf8_metadata ($cursection, "srcicon",  "_icon".$doc_ext."_"); 
    $doc_obj->add_utf8_metadata ($cursection, "/srclink", "</a>"); 

    return 1;
}

1;







