source: gsdl/trunk/perllib/plugins/ConvertBinaryFile.pm@ 15918

Last change on this file since 15918 was 15906, checked in by kjdon, 16 years ago

inherits from AutoExtractMetadata now, not BasePlugin

  • Property svn:keywords set to Author Date Id Revision
File size: 16.8 KB
Line 
1###########################################################################
2#
3# ConvertBinaryFile.pm -- plugin that facilitates conversion of binary files
4# through gsConvert.pl
5#
6# A component of the Greenstone digital library software
7# from the New Zealand Digital Library Project at the
8# University of Waikato, New Zealand.
9#
10# Copyright (C) 1999 New Zealand Digital Library Project
11#
12# This program is free software; you can redistribute it and/or modify
13# it under the terms of the GNU General Public License as published by
14# the Free Software Foundation; either version 2 of the License, or
15# (at your option) any later version.
16#
17# This program is distributed in the hope that it will be useful,
18# but WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20# GNU General Public License for more details.
21#
22# You should have received a copy of the GNU General Public License
23# along with this program; if not, write to the Free Software
24# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25#
26###########################################################################
27
28# This plugin is inherited by such plugins as WordPlug, PPTPlug, PSPlug,
29# RTFPlug and PDFPlug. It facilitates the conversion of these document types
30# to either HTML, Text or a series of images. It works by dynamically loading
31# an appropriate secondary plugin (HTMLPlug, StructuredHTMLPlug,
32# PagedImagePlugin or TextPlugin) based on the plugin argument 'convert_to'.
33
34package ConvertBinaryFile;
35
36use AutoExtractMetadata;
37use ghtml;
38use HTMLPlugin;
39use TextPlugin;
40use PagedImagePlugin;
41
42use strict;
43no strict 'refs'; # allow filehandles to be variables and viceversa
44no strict 'subs';
45
46sub BEGIN {
47 @ConvertBinaryFile::ISA = ('AutoExtractMetadata');
48}
49
50my $convert_to_list =
51 [ { 'name' => "auto",
52 'desc' => "{ConvertBinaryFile.convert_to.auto}" },
53 { 'name' => "html",
54 'desc' => "{ConvertBinaryFile.convert_to.html}" },
55 { 'name' => "text",
56 'desc' => "{ConvertBinaryFile.convert_to.text}" }
57 ];
58
59my $arguments =
60 [ { 'name' => "convert_to",
61 'desc' => "{ConvertBinaryFile.convert_to}",
62 'type' => "enum",
63 'reqd' => "yes",
64 'list' => $convert_to_list,
65 'deft' => "auto" },
66 { 'name' => "keep_original_filename",
67 'desc' => "{ConvertBinaryFile.keep_original_filename}",
68 'type' => "flag" },
69 { 'name' => "title_sub",
70 'desc' => "{HTMLPlug.title_sub}",
71 'type' => "string",
72 #'type' => "regexp",
73 'deft' => "" },
74 { 'name' => "apply_fribidi",
75 'desc' => "{ConvertBinaryFile.apply_fribidi}",
76 'type' => "flag",
77 'reqd' => "no" },
78 { 'name' => "use_strings",
79 'desc' => "{ConvertBinaryFile.use_strings}",
80 'type' => "flag",
81 'reqd' => "no" },
82 ];
83
84my $options = { 'name' => "ConvertBinaryFile",
85 'desc' => "{ConvertBinaryFile.desc}",
86 'abstract' => "yes",
87 'inherits' => "yes",
88 'args' => $arguments };
89
90
91sub load_secondary_plugins
92{
93 my $self = shift (@_);
94 my ($class,$input_args,$hashArgOptLists) = @_;
95
96 my @convert_to_list = split(",",$self->{'convert_to'});
97 my $secondary_plugins = {};
98 # find the plugin
99
100 foreach my $convert_to (@convert_to_list) {
101 # load in "convert_to" plugin package
102 my $plugin_class = $convert_to."Plugin";
103 my $plugin_package = $plugin_class.".pm";
104
105 my $colplugname = undef;
106 if (defined $ENV{'GSDLCOLLECTDIR'}) {
107 $colplugname = &util::filename_cat($ENV{'GSDLCOLLECTDIR'},
108 "perllib","plugins",
109 $plugin_package);
110 }
111
112 my $mainplugname = &util::filename_cat($ENV{'GSDLHOME'},
113 "perllib","plugins",
114 $plugin_package);
115
116 if ((defined $colplugname) && (-e $colplugname)) { require $colplugname;}
117 elsif (-e $mainplugname) { require $mainplugname; }
118 else {
119 &gsprintf(STDERR, "{plugin.could_not_find_plugin}\n",
120 $plugin_class);
121 die "\n";
122 }
123
124 # call its constructor with extra options that we've worked out!
125 my $arglist = $input_args->{$plugin_class};
126
127 my ($secondary_plugin);
128 eval("\$secondary_plugin = new $plugin_class([],\$arglist)");
129 die "$@" if $@;
130 $secondary_plugins->{$plugin_class} = $secondary_plugin;
131 }
132 $self->{'secondary_plugins'} = $secondary_plugins;
133}
134
135sub new {
136 my ($class) = shift (@_);
137 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
138 push(@$pluginlist, $class);
139 my $classPluginName = (defined $pluginlist->[0]) ? $pluginlist->[0] : $class;
140 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
141 push(@{$hashArgOptLists->{"OptList"}},$options);
142
143 my $self = new AutoExtractMetadata($pluginlist, $inputargs, $hashArgOptLists);
144
145 if ($self->{'info_only'}) {
146 # don't worry about any options etc
147 return bless $self, $class;
148 }
149
150 my $convert_to_type = $self->{'convert_to'};
151 if (!defined $convert_to_type || $convert_to_type eq "") {
152 $convert_to_type = "auto";
153 }
154 my $windows_scripting = $self->{'windows_scripting'};
155 $windows_scripting = 0 unless defined $windows_scripting;
156 if ($classPluginName eq "PDFPlugin") {
157 if ($convert_to_type eq "text" &&
158 $ENV{'GSDLOS'} =~ /^windows$/i) {
159 print STDERR "Windows does not support pdf to text. PDFs will be converted to HTML instead\n";
160 $convert_to_type = "html";
161 }
162 } elsif ($classPluginName eq "WordPlugin") {
163 if ($windows_scripting && $ENV{'GSDLOS'} =~ /^windows$/i && $convert_to_type =~ /^(html|auto)$/) {
164 # we use structured HTML, not normal html
165 $convert_to_type = "structuredhtml";
166 }
167 } elsif ($classPluginName eq "PPTPlugin") {
168 if ($windows_scripting && $ENV{'GSDLOS'} =~ /^windows$/i && $convert_to_type eq "auto") {
169 # we use paged img
170 $convert_to_type = "pagedimg_jpg";
171 }
172 } elsif ($classPluginName eq "PSPlugin") {
173 if ($convert_to_type eq "auto") {
174 # we use text
175 $convert_to_type = "text";
176 }
177 }
178
179 if ($convert_to_type eq "auto") {
180 # choose html for now - should choose a format based on doc type
181 $convert_to_type = "html";
182 }
183
184 if ($convert_to_type eq "html") {
185 $self->{'convert_to'} = "HTML";
186 $self->{'convert_to_ext'} = "html";
187 } elsif ($convert_to_type eq "text") {
188 $self->{'convert_to'} = "Text";
189 $self->{'convert_to_ext'} = "txt";
190 } elsif ($convert_to_type eq "structuredhtml") {
191 $self->{'convert_to'} = "StructuredHTML";
192 $self->{'convert_to_ext'} = "html";
193 } elsif ($convert_to_type =~ /^pagedimg/) {
194 $self->{'convert_to'} = "PagedImage";
195 my ($convert_to_ext) = $convert_to_type =~ /pagedimg\_(jpg|gif|png)/i;
196 $convert_to_ext = 'jpg' unless defined $convert_to_ext;
197 $self->{'convert_to_ext'} = $convert_to_ext;
198 }
199
200 return bless $self, $class;
201}
202
203
204sub init {
205 my $self = shift (@_);
206 my ($verbosity, $outhandle, $failhandle) = @_;
207
208 $self->SUPER::init($verbosity,$outhandle,$failhandle);
209
210 my $secondary_plugins = $self->{'secondary_plugins'};
211
212 foreach my $plug_name (keys %$secondary_plugins) {
213 my $plugin = $secondary_plugins->{$plug_name};
214 $plugin->init($verbosity,$outhandle,$failhandle);
215 }
216}
217
218sub deinit {
219 # called only once, after all plugin passes have been done
220
221 my ($self) = @_;
222
223 my $secondary_plugins = $self->{'secondary_plugins'};
224
225 foreach my $plug_name (keys %$secondary_plugins) {
226 my $plugin = $secondary_plugins->{$plug_name};
227 $plugin->deinit();
228 }
229}
230
231sub convert_post_process
232{
233 # by default do no post processing
234 return;
235}
236
237
238# Run conversion utility on the input file.
239#
240# The conversion takes place in a collection specific 'tmp' directory so
241# that we don't accidentally damage the input.
242#
243# The desired output type is indicated by $output_ext. This is usually
244# something like "html" or "word", but can be "best" (or the empty string)
245# to indicate that the conversion utility should do the best it can.
246sub tmp_area_convert_file {
247 my $self = shift (@_);
248 my ($output_ext, $input_filename, $textref) = @_;
249
250 my $outhandle = $self->{'outhandle'};
251 my $convert_to = $self->{'convert_to'};
252 my $failhandle = $self->{'failhandle'};
253 my $convert_to_ext = $self->{'convert_to_ext'};
254
255 # derive tmp filename from input filename
256 my ($tailname, $dirname, $suffix)
257 = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
258
259 # softlink to collection tmp dir
260 my $tmp_dirname = $dirname;
261 if(defined $ENV{'GSDLCOLLECTDIR'}) {
262 $tmp_dirname = $ENV{'GSDLCOLLECTDIR'};
263 } elsif(defined $ENV{'GSDLHOME'}) {
264 $tmp_dirname = $ENV{'GSDLHOME'};
265 }
266 $tmp_dirname = &util::filename_cat($tmp_dirname, "tmp");
267 &util::mk_dir($tmp_dirname) if (!-e $tmp_dirname);
268
269 # The following is not necessary and will cause problems with
270 # replacing_srcdoc_with_html in the GSDLremote case:
271 # Remove any white space from filename -- no risk of name collision, and
272 # makes later conversion by utils simpler. Leave spaces in path...
273 # tidy up the filename with space, dot, hyphen between
274 #$tailname =~ s/\s+//g;
275 #$tailname =~ s/\.+//g;
276 #$tailname =~ s/\-+//g;
277
278 # convert to utf-8 otherwise we have problems with the doc.xml file
279 # later on
280 &unicode::ensure_utf8(\$tailname);
281
282 $suffix = lc($suffix);
283 my $tmp_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
284
285 # If gsdl is remote, we're given relative path to input file, of the form import/tailname.suffix
286 # But we can't softlink to relative paths. Therefore, we need to ensure that
287 # the input_filename is the absolute path, see http://perldoc.perl.org/File/Spec.html
288 my $ensure_path_absolute = 1; # true
289 &util::soft_link($input_filename, $tmp_filename, $ensure_path_absolute);
290 my $verbosity = $self->{'verbosity'};
291 if ($verbosity > 0) {
292 print $outhandle "Converting $tailname$suffix to $convert_to format\n";
293 }
294
295 my $errlog = &util::filename_cat($tmp_dirname, "err.log");
296
297 # Execute the conversion command and get the type of the result,
298 # making sure the converter gives us the appropriate output type
299 my $output_type="";
300 if ($convert_to =~ m/PagedImage/i) {
301 $output_type = lc($convert_to)."_".lc($convert_to_ext);
302 } else {
303 $output_type = lc($convert_to);
304 }
305
306 my $cmd = "perl -S gsConvert.pl -verbose $verbosity ";
307 if (defined $self->{'convert_options'}) {
308 $cmd .= $self->{'convert_options'} . " ";
309 }
310 if ($self->{'use_strings'}) {
311 $cmd .= "-use_strings ";
312 }
313 $cmd .= "-errlog \"$errlog\" -output $output_type \"$tmp_filename\"";
314 $output_type = `$cmd`;
315
316 # remove symbolic link to original file
317 &util::rm($tmp_filename);
318
319 # Check STDERR here
320 chomp $output_type;
321 if ($output_type eq "fail") {
322 print $outhandle "Could not convert $tailname$suffix to $convert_to format\n";
323 print $failhandle "$tailname$suffix: " . ref($self) . " failed to convert to $convert_to\n";
324 # The following meant that if a conversion failed, the document would be counted twice - do we need it for anything?
325 #$self->{'num_not_processed'} ++;
326 if (-s "$errlog") {
327 open(ERRLOG, "$errlog");
328 while (<ERRLOG>) {
329 print $outhandle "$_";
330 }
331 print $outhandle "\n";
332 close ERRLOG;
333 }
334 &util::rm("$errlog") if (-e "$errlog");
335 return "";
336 }
337
338 # store the *actual* output type and return the output filename
339 # it's possible we requested conversion to html, but only to text succeeded
340 #$self->{'convert_to_ext'} = $output_type;
341 if ($output_type =~ /html/i) {
342 $self->{'converted_to'} = "HTML";
343 } elsif ($output_type =~ /te?xt/i) {
344 $self->{'converted_to'} = "Text";
345 } elsif ($output_type =~ /item/i){
346 $self->{'converted_to'} = "PagedImage";
347 }
348
349 my $output_filename = $tmp_filename;
350 if ($output_type =~ /item/i) {
351 # running under windows
352 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
353 $output_filename = $tmp_dirname . "\\$tailname\\" . $tailname . ".$output_type";
354 } else {
355 $output_filename = $tmp_dirname . "\/$tailname\/" . $tailname . ".$output_type";
356 }
357 } else {
358 $output_filename =~ s/$suffix$/.$output_type/;
359 }
360
361 return $output_filename;
362}
363
364
365# Override BasPlug read_into_doc_obj - we need to call secondary plugin stuff
366sub read_into_doc_obj {
367 my $self = shift (@_);
368 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
369
370 my $outhandle = $self->{'outhandle'};
371
372 my ($filename_full_path, $filename_no_path) = $self->get_full_filenames($base_dir, $file);
373
374 my $output_ext = $self->{'convert_to_ext'};
375 my $conv_filename = "";
376 $conv_filename = $self->tmp_area_convert_file($output_ext, $filename_full_path);
377
378 if ("$conv_filename" eq "") {return -1;} # had an error, will be passed down pipeline
379 if (! -e "$conv_filename") {return -1;}
380 $self->{'conv_filename'} = $conv_filename;
381 $self->convert_post_process($conv_filename);
382
383 # Run the "fribidi" (http://fribidi.org) Unicode Bidirectional Algorithm program over the converted file
384 # Added for fixing up Persian PDFs after being processed by pdftohtml, but may be useful in other cases too
385 if ($self->{'apply_fribidi'} && $self->{'converted_to'} =~ /(HTML|Text)/) {
386 my $fribidi_command = "fribidi \"$conv_filename\" >\"${conv_filename}.tmp\"";
387 if (system($fribidi_command) != 0) {
388 print STDERR "ERROR: Cannot run fribidi on \"$conv_filename\".\n";
389 }
390 else {
391 &util::mv("${conv_filename}.tmp", $conv_filename);
392 }
393 }
394
395 my $secondary_plugins = $self->{'secondary_plugins'};
396 my $num_secondary_plugins = scalar(keys %$secondary_plugins);
397
398 if ($num_secondary_plugins == 0) {
399 print $outhandle "Warning: No secondary plugin to use in conversion. Skipping $file\n";
400 return 0; # effectively block it
401 }
402
403 my @plugin_names = keys %$secondary_plugins;
404 my $plugin_name = shift @plugin_names;
405
406 if ($num_secondary_plugins > 1) {
407 print $outhandle "Warning: Multiple secondary plugins not supported yet! Choosing $plugin_name\n.";
408 }
409
410 my $secondary_plugin = $secondary_plugins->{$plugin_name};
411
412 # note: metadata is not carried on to the next level
413 my ($rv,$doc_obj)
414 = $secondary_plugin->read_into_doc_obj ($pluginfo,"", $conv_filename, $metadata, $processor, $maxdocs, $total_count, $gli);
415
416 if ((!defined $rv) || ($rv<1)) {
417 # wasn't processed
418 return $rv;
419 }
420
421 # Override previous gsdlsourcefilename set by secondary plugin
422 my $collect_file = &util::filename_within_collection($filename_full_path);
423 my $collect_conv_file = &util::filename_within_collection($conv_filename);
424 $doc_obj->set_source_filename ($collect_file);
425 $doc_obj->set_converted_filename($collect_conv_file);
426
427 $self->set_Source_metadata($doc_obj, $filename_no_path);
428
429 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
430 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "FileSize", (-s $filename_full_path));
431
432 # do plugin specific processing of doc_obj
433 unless (defined ($self->process($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
434 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
435 return -1;
436 }
437
438 my $topsection = $doc_obj->get_top_section();
439 $self->add_associated_files($doc_obj, $filename_full_path);
440 $self->extra_metadata($doc_obj, $topsection, $metadata); # do we need this here??
441 # do any automatic metadata extraction
442 $self->auto_extract_metadata ($doc_obj);
443
444 # have we found a Title??
445 $self->title_fallback($doc_obj,$topsection,$filename_no_path);
446
447 $self->add_OID($doc_obj);
448
449 return (1, $doc_obj);
450
451}
452
453sub process {
454 my $self = shift (@_);
455 my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
456
457 return $self->process_type($base_dir, $file, $doc_obj);
458}
459
460# do plugin specific processing of doc_obj for doc_ext type
461sub process_type {
462 my $self = shift (@_);
463 my ($base_dir, $file, $doc_obj) = @_;
464
465 # need to check that not empty
466 my $doc_ext = $self->{'filename_extension'};
467 my $file_type = "unknown";
468 $file_type = $self->{'file_type'} if defined $self->{'file_type'};
469
470 # associate original file with doc object
471 my $cursection = $doc_obj->get_top_section();
472 my $filename = &util::filename_cat($base_dir, $file);
473 my $assocfilename = "doc.$doc_ext";
474 if ($self->{'keep_original_filename'} == 1) {
475 # this should be the same filename that was used for the Source metadata, as we will use [Source] in the srclink
476 ($assocfilename) = $file =~ /([^\\\/]+)$/;
477 }
478 $doc_obj->associate_file($filename, $assocfilename, undef, $cursection);
479
480 # We use set instead of add here because we only want one value
481 $doc_obj->set_utf8_metadata_element($cursection, "FileFormat", $file_type);
482 my $doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/[archivedir]/doc.$doc_ext\">";
483 if ($self->{'keep_original_filename'} == 1) {
484 $doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/[archivedir]/[Source]\">";
485 }
486 $doc_obj->add_utf8_metadata ($cursection, "srclink", $doclink);
487 $doc_obj->add_utf8_metadata ($cursection, "srcicon", "_icon".$doc_ext."_");
488 $doc_obj->add_utf8_metadata ($cursection, "/srclink", "</a>");
489
490 return 1;
491}
492
4931;
494
495
496
497
498
499
500
Note: See TracBrowser for help on using the repository browser.