source: gsdl/trunk/perllib/plugins/ConvertToPlug.pm@ 14928

Last change on this file since 14928 was 14928, checked in by davidb, 16 years ago

ConvertToPlug upgraded to be the same as BasPlug in regard to calling set_OID id defined for the method that set's a documents ID

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