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

Last change on this file since 12610 was 12169, checked in by mdewsnip, 18 years ago

Tidied up that horrible long line in the new() function of every plugin.

  • Property svn:keywords set to Author Date Id Revision
File size: 16.0 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, RTFPlug
28# and PDFPlug. It facilitates the conversion of these document types to either
29# HTML, Text or auto (allow user to choose which format to convert to).
30# It works by dynamically inheriting BasPlug and base on the plugin type in
31# secondary_plugins to devide which format to 'convert_to'. If the argument is
32# not present, the default is to inherit auto.
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' => "title_sub",
65 'desc' => "{HTMLPlug.title_sub}",
66 'type' => "string",
67 #'type' => "regexp",
68 'deft' => "" },
69 { 'name' => "apply_fribidi",
70 'desc' => "{ConvertToPlug.apply_fribidi}",
71 'type' => "flag",
72 'reqd' => "no" },
73 { 'name' => "use_strings",
74 'desc' => "{ConvertToPlug.use_strings}",
75 'type' => "flag",
76 'reqd' => "no" },
77 { 'name' => "extract_keyphrases",
78 'desc' => "{BasPlug.extract_keyphrases}",
79 'type' => "flag",
80 'reqd' => "no",
81 'hiddengli' => "yes" },
82 { 'name' => "extract_keyphrase_options",
83 'desc' => "{BasPlug.extract_keyphrase_options}",
84 'type' => "string",
85 'reqd' => "no",
86 'hiddengli' => "yes" } ];
87
88my $options = { 'name' => "ConvertToPlug",
89 'desc' => "{ConvertToPlug.desc}",
90 'abstract' => "yes",
91 'inherits' => "yes",
92 'args' => $arguments };
93
94
95sub load_secondary_plugins
96{
97 my $self = shift (@_);
98 my ($class,$input_args,$hashArgOptLists) = @_;
99
100 my @convert_to_list = split(",",$self->{'convert_to'});
101 my $secondary_plugins = {};
102 # find the plugin
103
104 foreach my $convert_to (@convert_to_list) {
105 # load in "convert_to" plugin package
106 my $plugin_class = $convert_to."Plug";
107 my $plugin_package = $plugin_class.".pm";
108
109 my $colplugname = &util::filename_cat($ENV{'GSDLCOLLECTDIR'},
110 "perllib/plugins",
111 $plugin_package);
112 my $mainplugname = &util::filename_cat($ENV{'GSDLHOME'},
113 "perllib/plugins",
114 $plugin_package);
115
116 if (-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 if(defined $arguments){ push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});}
141 if(defined $options) { push(@{$hashArgOptLists->{"OptList"}},$options)};
142
143 my $self = new BasPlug($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 "PDFPlug") {
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 "WordPlug") {
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 "PPTPlug") {
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 "PSPlug") {
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'} = "PagedImg";
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 # softlink to collection tmp dir
256 my $tmp_dirname
257 = &util::filename_cat($ENV{'GSDLCOLLECTDIR'}, "tmp");
258 &util::mk_dir($tmp_dirname) if (!-e $tmp_dirname);
259
260 # derive tmp filename from input filename
261 my ($tailname, $dirname, $suffix)
262 = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
263
264 # Remove any white space from filename -- no risk of name collision, and
265 # makes later conversion by utils simpler. Leave spaces in path...
266 # tidy up the filename with space, dot, hyphen between
267 $tailname =~ s/\s+//g;
268 $tailname =~ s/\.+//g;
269 $tailname =~ s/\-+//g;
270 $suffix = lc($suffix);
271 my $tmp_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
272 &util::soft_link($input_filename, $tmp_filename);
273 my $verbosity = $self->{'verbosity'};
274 if ($verbosity > 0) {
275 print $outhandle "Converting $tailname$suffix to $convert_to format\n";
276 }
277
278 my $errlog = &util::filename_cat($tmp_dirname, "err.log");
279
280 # Execute the conversion command and get the type of the result,
281 # making sure the converter gives us the appropriate output type
282 my $output_type="";
283 if ($convert_to =~ m/PagedImg/i) {
284 $output_type = lc($convert_to)."_".lc($convert_to_ext);
285 } else {
286 $output_type = lc($convert_to);
287 }
288
289 my $cmd = "perl -S gsConvert.pl -verbose $verbosity ";
290 if (defined $self->{'convert_options'}) {
291 $cmd .= $self->{'convert_options'} . " ";
292 }
293 if ($self->{'use_strings'}) {
294 $cmd .= "-use_strings ";
295 }
296 $cmd .= "-errlog \"$errlog\" -output $output_type \"$tmp_filename\"";
297
298 $output_type = `$cmd`;
299
300 # remove symbolic link to original file
301 &util::rm($tmp_filename);
302
303 # Check STDERR here
304 chomp $output_type;
305 if ($output_type eq "fail") {
306 print $outhandle "Could not convert $tailname$suffix to $convert_to format\n";
307 print $failhandle "$tailname$suffix: " . ref($self) . " failed to convert to $convert_to\n";
308 # The following meant that if a conversion failed, the document would be counted twice - do we need it for anything?
309 #$self->{'num_not_processed'} ++;
310 if (-s "$errlog") {
311 open(ERRLOG, "$errlog");
312 while (<ERRLOG>) {
313 print $outhandle "$_";
314 }
315 print $outhandle "\n";
316 close ERRLOG;
317 }
318 &util::rm("$errlog") if (-e "$errlog");
319 return "";
320 }
321
322 # store the *actual* output type and return the output filename
323 # it's possible we requested conversion to html, but only to text succeeded
324 #$self->{'convert_to_ext'} = $output_type;
325 if ($output_type =~ /html/i) {
326 $self->{'converted_to'} = "HTML";
327 } elsif ($output_type =~ /te?xt/i) {
328 $self->{'converted_to'} = "TEXT";
329 } elsif ($output_type =~ /item/i){
330 $self->{'converted_to'} = "PagedImg";
331 }
332
333 my $output_filename = $tmp_filename;
334 if ($output_type =~ /item/i) {
335 # running under windows
336 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
337 $output_filename = $tmp_dirname . "\\$tailname\\" . $tailname . ".$output_type";
338 } else {
339 $output_filename = $tmp_dirname . "\/$tailname\/" . $tailname . ".$output_type";
340 }
341 } else {
342 $output_filename =~ s/$suffix$/.$output_type/;
343 }
344 return $output_filename;
345}
346
347
348# Override BasPlug read
349# We don't want to get language encoding stuff until after we've converted
350# our file to either TEXT or HTML or PagedImage.
351sub read {
352 my $self = shift (@_);
353 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
354
355 my $outhandle = $self->{'outhandle'};
356
357 my ($block_status,$filename) = $self->read_block(@_);
358 return $block_status if ((!defined $block_status) || ($block_status==0));
359 $file = $self->read_tidy_file($file);
360
361 my $output_ext = $self->{'convert_to_ext'};
362 my $conv_filename = "";
363 $conv_filename = $self->tmp_area_convert_file($output_ext, $filename);
364
365 if ("$conv_filename" eq "") {return -1;} # had an error, will be passed down pipeline
366 if (! -e "$conv_filename") {return -1;}
367 $self->{'conv_filename'} = $conv_filename;
368 $self->convert_post_process($conv_filename);
369
370 # Run the "fribidi" (http://fribidi.org) Unicode Bidirectional Algorithm program over the converted file
371 # Added for fixing up Persian PDFs after being processed by pdftohtml, but may be useful in other cases too
372 if ($self->{'apply_fribidi'} && $self->{'converted_to'} =~ /(HTML|TEXT)/) {
373 my $fribidi_command = "fribidi \"$conv_filename\" >\"${conv_filename}.tmp\"";
374 if (system($fribidi_command) != 0) {
375 print STDERR "ERROR: Cannot run fribidi on \"$conv_filename\".\n";
376 }
377 else {
378 &util::mv("${conv_filename}.tmp", $conv_filename);
379 }
380 }
381
382 my $secondary_plugins = $self->{'secondary_plugins'};
383 my $num_secondary_plugins = scalar(keys %$secondary_plugins);
384
385 if ($num_secondary_plugins == 0) {
386 print $outhandle "Warning: No secondary plugin to use in conversion. Skipping $file\n";
387 return 0; # effectively block it
388 }
389
390 my @plugin_names = keys %$secondary_plugins;
391 my $plugin_name = shift @plugin_names;
392
393 if ($num_secondary_plugins > 1) {
394 print $outhandle "Warning: Multiple secondary plugins not supported yet! Choosing $plugin_name\n.";
395 }
396
397 my $secondary_plugin = $secondary_plugins->{$plugin_name};
398
399 # note: metadata is not carried on to the next level
400 my ($rv,$doc_obj)
401 = $secondary_plugin->read_into_doc_obj ($pluginfo,"", $conv_filename,
402 $metadata, $processor, $maxdocs, $total_count,
403 $gli);
404
405 if ((!defined $rv) || ($rv<1)) {
406 # wasn't processed
407 return $rv;
408 }
409
410 # Override previous gsdlsourcefilename set by secondary plugin
411 my $collect_file = &util::filename_within_collection($filename);
412 my $collect_conv_file = &util::filename_within_collection($conv_filename);
413 $doc_obj->set_source_filename ($collect_file);
414 $doc_obj->set_converted_filename($collect_conv_file);
415
416 my ($filemeta) = $file =~ /([^\\\/]+)$/;
417 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Source", &ghtml::dmsafe($filemeta));
418 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
419 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "FileSize", (-s $filename));
420
421 if ($self->{'cover_image'}) {
422 $self->associate_cover_image($doc_obj, $filename);
423 }
424
425 # do plugin specific processing of doc_obj
426 unless (defined ($self->process(undef, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
427 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
428 return -1;
429 }
430 # do any automatic metadata extraction
431 $self->auto_extract_metadata ($doc_obj);
432
433 # have we found a Title??
434 $self->title_fallback($doc_obj,$doc_obj->get_top_section(),$filemeta);
435
436 # add an OID
437 $doc_obj->set_OID();
438 # process the document
439 $processor->process($doc_obj);
440
441 $self->{'num_processed'} ++;
442
443 return 1;
444}
445
446
447# do plugin specific processing of doc_obj for doc_ext type
448sub process_type {
449 my $self = shift (@_);
450 my ($doc_ext, $base_dir, $file, $doc_obj) = @_;
451
452 # associate original file with doc object
453 my $cursection = $doc_obj->get_top_section();
454 my $filename = &util::filename_cat($base_dir, $file);
455 $doc_obj->associate_file($filename, "doc.$doc_ext", undef, $cursection);
456
457 my $file_type;
458
459 if ($doc_ext eq "doc") {
460 $file_type = "Word";
461 } elsif ($doc_ext eq "xls") {
462 $file_type = "Excel";
463 } elsif ($doc_ext eq "ppt") {
464 $file_type = "PPT";
465 } elsif ($doc_ext eq "pdf") {
466 $file_type = "PDF";
467 } elsif ($doc_ext eq "rtf") {
468 $file_type = "RTF";
469 } elsif ($doc_ext eq "ps") {
470 $file_type = "PS";
471 }
472
473 my $file_format = $file_type || "unknown";
474
475 # We use set instead of add here because we only want one value
476 $doc_obj->set_utf8_metadata_element($cursection, "FileFormat", $file_format);
477
478 my $doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/[archivedir]/doc.$doc_ext\">";
479 $doc_obj->add_utf8_metadata ($cursection, "srclink", $doclink);
480 $doc_obj->add_utf8_metadata ($cursection, "srcicon", "_icon".$doc_ext."_");
481 $doc_obj->add_utf8_metadata ($cursection, "/srclink", "</a>");
482
483 return 1;
484}
485
4861;
487
488
489
490
491
492
493
Note: See TracBrowser for help on using the repository browser.