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

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

plugin overhaul: Split plug renamed to SplitTextFile, XMLPlug renamed to ReadXMLFile, ConvertToPlug renamed to ConvertBinaryFile. With the exception of BasePlugin, only 'real' plugins (top level ones) are named xxPlugin.

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