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

Last change on this file since 16922 was 16922, checked in by ak19, 16 years ago
  1. The doclink uses the new SourceFile metadata, which is the url-encoded reference to the associated file's name on the filesystem (which may itself be url-encoded originally). 2. The assocfilename calls the doc_obj's new method assocfile_from_sourcefile() to determine the name of the associate file from the SourceFile metadata (the SourceFile metadata being the url ref to the filename).
  • Property svn:keywords set to Author Date Id Revision
File size: 17.5 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' => "{HTMLPlugin.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 later on
279# print STDERR "**** filename $tailname$suffix is already UTF8\n" if &unicode::check_is_utf8($tailname);
280 $tailname = $self->SUPER::filepath_to_utf8($tailname) unless &unicode::check_is_utf8($tailname);
281
282 # URLEncode this since htmls with images where the html filename is utf8 don't seem
283 # to work on Windows (IE or Firefox), as browsers are looking for filesystem-encoded
284 # files on the filesystem.
285 $tailname = &unicode::url_encode($tailname);
286
287 $suffix = lc($suffix);
288 my $tmp_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
289
290 # If gsdl is remote, we're given relative path to input file, of the form import/tailname.suffix
291 # But we can't softlink to relative paths. Therefore, we need to ensure that
292 # the input_filename is the absolute path, see http://perldoc.perl.org/File/Spec.html
293 my $ensure_path_absolute = 1; # true
294 &util::soft_link($input_filename, $tmp_filename, $ensure_path_absolute);
295 my $verbosity = $self->{'verbosity'};
296 if ($verbosity > 0) {
297 print $outhandle "Converting $tailname$suffix to $convert_to format\n";
298 }
299
300 my $errlog = &util::filename_cat($tmp_dirname, "err.log");
301
302 # Execute the conversion command and get the type of the result,
303 # making sure the converter gives us the appropriate output type
304 my $output_type="";
305 if ($convert_to =~ m/PagedImage/i) {
306 $output_type = lc($convert_to)."_".lc($convert_to_ext);
307 } else {
308 $output_type = lc($convert_to);
309 }
310
311 my $cmd = "perl -S gsConvert.pl -verbose $verbosity ";
312 if (defined $self->{'convert_options'}) {
313 $cmd .= $self->{'convert_options'} . " ";
314 }
315 if ($self->{'use_strings'}) {
316 $cmd .= "-use_strings ";
317 }
318 $cmd .= "-errlog \"$errlog\" -output $output_type \"$tmp_filename\"";
319 $output_type = `$cmd`;
320
321 # remove symbolic link to original file
322 &util::rm($tmp_filename);
323
324 # Check STDERR here
325 chomp $output_type;
326 if ($output_type eq "fail") {
327 print $outhandle "Could not convert $tailname$suffix to $convert_to format\n";
328 print $failhandle "$tailname$suffix: " . ref($self) . " failed to convert to $convert_to\n";
329 # The following meant that if a conversion failed, the document would be counted twice - do we need it for anything?
330 #$self->{'num_not_processed'} ++;
331 if (-s "$errlog") {
332 open(ERRLOG, "$errlog");
333 while (<ERRLOG>) {
334 print $outhandle "$_";
335 }
336 print $outhandle "\n";
337 close ERRLOG;
338 }
339 &util::rm("$errlog") if (-e "$errlog");
340 return "";
341 }
342
343 # store the *actual* output type and return the output filename
344 # it's possible we requested conversion to html, but only to text succeeded
345 #$self->{'convert_to_ext'} = $output_type;
346 if ($output_type =~ /html/i) {
347 $self->{'converted_to'} = "HTML";
348 } elsif ($output_type =~ /te?xt/i) {
349 $self->{'converted_to'} = "Text";
350 } elsif ($output_type =~ /item/i){
351 $self->{'converted_to'} = "PagedImage";
352 }
353
354 my $output_filename = $tmp_filename;
355 if ($output_type =~ /item/i) {
356 # running under windows
357 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
358 $output_filename = $tmp_dirname . "\\$tailname\\" . $tailname . ".$output_type";
359 } else {
360 $output_filename = $tmp_dirname . "\/$tailname\/" . $tailname . ".$output_type";
361 }
362 } else {
363 $output_filename =~ s/$suffix$/.$output_type/;
364 }
365
366 return $output_filename;
367}
368
369
370# Override BasPlug read_into_doc_obj - we need to call secondary plugin stuff
371sub read_into_doc_obj {
372 my $self = shift (@_);
373 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
374
375 my $outhandle = $self->{'outhandle'};
376
377 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
378
379 my $output_ext = $self->{'convert_to_ext'};
380 my $conv_filename = "";
381 $conv_filename = $self->tmp_area_convert_file($output_ext, $filename_full_path);
382
383 if ("$conv_filename" eq "") {return -1;} # had an error, will be passed down pipeline
384 if (! -e "$conv_filename") {return -1;}
385 $self->{'conv_filename'} = $conv_filename;
386 $self->convert_post_process($conv_filename);
387
388 # Run the "fribidi" (http://fribidi.org) Unicode Bidirectional Algorithm program over the converted file
389 # Added for fixing up Persian PDFs after being processed by pdftohtml, but may be useful in other cases too
390 if ($self->{'apply_fribidi'} && $self->{'converted_to'} =~ /(HTML|Text)/) {
391 my $fribidi_command = "fribidi \"$conv_filename\" >\"${conv_filename}.tmp\"";
392 if (system($fribidi_command) != 0) {
393 print STDERR "ERROR: Cannot run fribidi on \"$conv_filename\".\n";
394 }
395 else {
396 &util::mv("${conv_filename}.tmp", $conv_filename);
397 }
398 }
399
400 my $secondary_plugins = $self->{'secondary_plugins'};
401 my $num_secondary_plugins = scalar(keys %$secondary_plugins);
402
403 if ($num_secondary_plugins == 0) {
404 print $outhandle "Warning: No secondary plugin to use in conversion. Skipping $file\n";
405 return 0; # effectively block it
406 }
407
408 my @plugin_names = keys %$secondary_plugins;
409 my $plugin_name = shift @plugin_names;
410
411 if ($num_secondary_plugins > 1) {
412 print $outhandle "Warning: Multiple secondary plugins not supported yet! Choosing $plugin_name\n.";
413 }
414
415 my $secondary_plugin = $secondary_plugins->{$plugin_name};
416
417 # note: metadata is not carried on to the next level
418## **** I just replaced $metadata with {} in following
419 my ($rv,$doc_obj)
420 = $secondary_plugin->read_into_doc_obj ($pluginfo,"", $conv_filename, $block_hash, {}, $processor, $maxdocs, $total_count, $gli);
421
422 if ((!defined $rv) || ($rv<1)) {
423 # wasn't processed
424 return $rv;
425 }
426
427 # Override previous gsdlsourcefilename set by secondary plugin
428 my $collect_file = &util::filename_within_collection($filename_full_path);
429 my $collect_conv_file = &util::filename_within_collection($conv_filename);
430 $doc_obj->set_source_filename ($collect_file);
431 $doc_obj->set_converted_filename($collect_conv_file);
432
433 $self->set_Source_metadata($doc_obj, $filename_no_path);
434
435 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
436 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "FileSize", (-s $filename_full_path));
437
438 # do plugin specific processing of doc_obj
439 unless (defined ($self->process($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
440 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
441 return -1;
442 }
443
444 my $topsection = $doc_obj->get_top_section();
445 $self->add_associated_files($doc_obj, $filename_full_path);
446
447 # extra_metadata is already called by sec plugin in process??
448 $self->extra_metadata($doc_obj, $topsection, $metadata); # do we need this here??
449 # do any automatic metadata extraction
450 $self->auto_extract_metadata ($doc_obj);
451
452 # have we found a Title??
453 $self->title_fallback($doc_obj,$topsection,$filename_no_path);
454
455 $self->add_OID($doc_obj);
456
457 return (1, $doc_obj);
458
459}
460
461sub process {
462 my $self = shift (@_);
463 my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
464
465 return $self->process_type($base_dir, $file, $doc_obj);
466}
467
468# do plugin specific processing of doc_obj for doc_ext type
469sub process_type {
470 my $self = shift (@_);
471 my ($base_dir, $file, $doc_obj) = @_;
472
473 # need to check that not empty
474 my $doc_ext = $self->{'filename_extension'};
475 my $file_type = "unknown";
476 $file_type = $self->{'file_type'} if defined $self->{'file_type'};
477
478 # associate original file with doc object
479 my $cursection = $doc_obj->get_top_section();
480 my $filename = &util::filename_cat($base_dir, $file);
481 my $assocfilename = "doc.$doc_ext";
482 if ($self->{'keep_original_filename'} == 1) {
483 # this should be the same filename that was used for the Source and SourceFile metadata,
484 # as we will use [SourceFile] in the srclink
485 $assocfilename = $doc_obj->assocfile_from_sourcefile(); #($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]/[SourceFile]\">";
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.