source: gsdl/trunk/perllib/plugins/BasePlugin.pm@ 16698

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

added auxiliary parameter to new - needed if you want to do new without parsing the arguments - ie want to inherit from a plugin to get the methods and arguments, but its not in the direct inheritance line

  • Property svn:keywords set to Author Date Id Revision
File size: 33.0 KB
Line 
1###########################################################################
2#
3# BasePlugin.pm -- base class for all the import plugins
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 1999-2005 New Zealand Digital Library Project
9#
10# This program is free software; you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25
26package BasePlugin;
27
28use strict;
29no strict 'subs';
30no strict 'refs'; # allow filehandles to be variables and viceversa
31
32use File::Basename;
33
34use encodings;
35use unicode;
36use textcat;
37use doc;
38use ghtml;
39use gsprintf 'gsprintf';
40
41use PrintInfo;
42
43BEGIN {
44 @BasePlugin::ISA = ( 'PrintInfo' );
45}
46
47our $encoding_list =
48 [ { 'name' => "ascii",
49 'desc' => "{BasePlugin.encoding.ascii}" },
50 { 'name' => "utf8",
51 'desc' => "{BasePlugin.encoding.utf8}" },
52 { 'name' => "unicode",
53 'desc' => "{BasePlugin.encoding.unicode}" } ];
54
55
56my $e = $encodings::encodings;
57foreach my $enc (sort {$e->{$a}->{'name'} cmp $e->{$b}->{'name'}} keys (%$e))
58{
59 my $hashEncode =
60 {'name' => $enc,
61 'desc' => $e->{$enc}->{'name'}};
62
63 push(@{$encoding_list},$hashEncode);
64}
65
66our $encoding_plus_auto_list =
67 [ { 'name' => "auto",
68 'desc' => "{BasePlugin.filename_encoding.auto}" },
69 { 'name' => "auto-language-analysis",
70 'desc' => "{BasePlugin.filename_encoding.auto_language_analysis}" }, # textcat
71 { 'name' => "auto-filesystem-encoding",
72 'desc' => "{BasePlugin.filename_encoding.auto_filesystem_encoding}" }, # locale
73 { 'name' => "auto-fl",
74 'desc' => "{BasePlugin.filename_encoding.auto_fl}" }, # locale followed by textcat
75 { 'name' => "auto-lf",
76 'desc' => "{BasePlugin.filename_encoding.auto_lf}" } ]; # texcat followed by locale
77
78push(@{$encoding_plus_auto_list},@{$encoding_list});
79
80our $oidtype_list =
81 [ { 'name' => "hash",
82 'desc' => "{import.OIDtype.hash}" },
83 { 'name' => "assigned",
84 'desc' => "{import.OIDtype.assigned}" },
85 { 'name' => "incremental",
86 'desc' => "{import.OIDtype.incremental}" },
87 { 'name' => "dirname",
88 'desc' => "{import.OIDtype.dirname}" } ];
89
90my $arguments =
91 [ { 'name' => "process_exp",
92 'desc' => "{BasePlugin.process_exp}",
93 'type' => "regexp",
94 'deft' => "",
95 'reqd' => "no" },
96 { 'name' => "no_blocking",
97 'desc' => "{BasePlugin.no_blocking}",
98 'type' => "flag",
99 'reqd' => "no"},
100 { 'name' => "block_exp",
101 'desc' => "{BasePlugin.block_exp}",
102 'type' => "regexp",
103 'deft' => "",
104 'reqd' => "no" },
105 { 'name' => "associate_ext",
106 'desc' => "{BasePlugin.associate_ext}",
107 'type' => "string",
108 'reqd' => "no" },
109 { 'name' => "associate_tail_re",
110 'desc' => "{BasePlugin.associate_tail_re}",
111 'type' => "string",
112 'reqd' => "no" },
113 { 'name' => "OIDtype",
114 'desc' => "{import.OIDtype}",
115 'type' => "enum",
116 'list' => $oidtype_list,
117 # parsearg left "" as default
118 #'deft' => "hash",
119 'reqd' => "no",
120 'modegli' => "2" },
121 { 'name' => "OIDmetadata",
122 'desc' => "{import.OIDmetadata}",
123 'type' => "metadata",
124 'deft' => "dc.Identifier",
125 'reqd' => "no",
126 'modegli' => "2" },
127
128# { 'name' => "use_as_doc_identifier",
129# 'desc' => "{BasePlugin.use_as_doc_identifier}",
130# 'type' => "string",
131# 'reqd' => "no" ,
132# 'deft' => "" } ,
133 { 'name' => "no_cover_image",
134 'desc' => "{BasePlugin.no_cover_image}",
135 'type' => "flag",
136 'reqd' => "no" },
137 { 'name' => "filename_encoding",
138 'desc' => "{BasePlugin.filename_encoding}",
139 'type' => "enum",
140 'deft' => "auto",
141 'list' => $encoding_plus_auto_list,
142 'reqd' => "no" },
143 { 'name' => "smart_block",
144 'desc' => "{common.deprecated}. {BasePlugin.smart_block}",
145 'type' => "flag",
146 'reqd' => "no",
147 'hiddengli' => "yes" } # deprecated, but leave in for old collections
148
149
150 ];
151
152
153my $options = { 'name' => "BasePlugin",
154 'desc' => "{BasePlugin.desc}",
155 'abstract' => "yes",
156 'inherits' => "no",
157 'args' => $arguments };
158
159
160sub new {
161
162 my ($class) = shift (@_);
163 my ($pluginlist,$inputargs,$hashArgOptLists,$auxiliary) = @_;
164 push(@$pluginlist, $class);
165
166 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
167 push(@{$hashArgOptLists->{"OptList"}},$options);
168
169 my $self = new PrintInfo($pluginlist, $inputargs, $hashArgOptLists,$auxiliary);
170
171 if ($self->{'info_only'}) {
172 # don't worry about any options etc
173 return bless $self, $class;
174 }
175
176 if ($self->{'smart_block'}) {
177 print STDERR "WARNING: -smart_block option has been deprecated and is no longer useful\n";
178 }
179 $self->{'smart_block'} = undef;
180
181 my $plugin_name = (defined $pluginlist->[0]) ? $pluginlist->[0] : $class;
182 $self->{'plugin_type'} = $plugin_name;
183
184 $self->{'num_processed'} = 0;
185 $self->{'num_not_processed'} = 0;
186 $self->{'num_blocked'} = 0;
187 $self->{'num_archives'} = 0;
188 $self->{'cover_image'} = 1; # cover image is on by default
189 $self->{'cover_image'} = 0 if ($self->{'no_cover_image'});
190 #$self->{'option_list'} = $hashArgOptLists->{"OptList"};
191
192 my $associate_ext = $self->{'associate_ext'};
193 if ((defined $associate_ext) && ($associate_ext ne "")) {
194
195 my $associate_tail_re = $self->{'associate_tail_re'};
196 if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
197 my $outhandle = $self->{'outhandle'};
198 print $outhandle "Warning: can only specify 'associate_ext' or 'associate_tail_re'\n";
199 print $outhandle " defaulting to 'associate_tail_re'\n";
200 }
201 else {
202 my @exts = split(/,/,$associate_ext);
203
204 my @exts_bracketed = map { $_ = "(?:\\.$_)" } @exts;
205 my $associate_tail_re = join("|",@exts_bracketed);
206 $self->{'associate_tail_re'} = $associate_tail_re;
207 }
208
209 delete $self->{'associate_ext'};
210 }
211
212 return bless $self, $class;
213
214}
215
216# initialize BasePlugin options
217# if init() is overridden in a sub-class, remember to call BasePlugin::init()
218sub init {
219 my $self = shift (@_);
220 my ($verbosity, $outhandle, $failhandle) = @_;
221
222 # verbosity is passed through from the processor
223 $self->{'verbosity'} = $verbosity;
224
225 # as are the outhandle and failhandle
226 $self->{'outhandle'} = $outhandle if defined $outhandle;
227 $self->{'failhandle'} = $failhandle;
228# $self->SUPER::init(@_);
229
230 # set process_exp and block_exp to defaults unless they were
231 # explicitly set
232
233 if ((!$self->is_recursive()) and
234 (!defined $self->{'process_exp'}) || ($self->{'process_exp'} eq "")) {
235
236 $self->{'process_exp'} = $self->get_default_process_exp ();
237 if ($self->{'process_exp'} eq "") {
238 warn ref($self) . " Warning: Non-recursive plugin has no process_exp\n";
239 }
240 }
241
242 if ((!defined $self->{'block_exp'}) || ($self->{'block_exp'} eq "")) {
243 $self->{'block_exp'} = $self->get_default_block_exp ();
244 }
245
246}
247
248sub begin {
249 my $self = shift (@_);
250 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
251}
252
253sub end {
254 # potentially called at the end of each plugin pass
255 # import.pl only has one plugin pass, but buildcol.pl has multiple ones
256
257 my ($self) = shift (@_);
258}
259
260sub deinit {
261 # called only once, after all plugin passes have been done
262
263 my ($self) = @_;
264}
265
266sub set_incremental {
267 my $self = shift(@_);
268 my ($incremental) = @_;
269
270 $self->{'incremental'} = $incremental;
271}
272
273# this function should be overridden to return 1
274# in recursive plugins
275sub is_recursive {
276 my $self = shift (@_);
277
278 return 0;
279}
280
281sub get_default_block_exp {
282 my $self = shift (@_);
283
284 return "";
285}
286
287sub get_default_process_exp {
288 my $self = shift (@_);
289
290 return "";
291}
292
293# default implementation is to do nothing
294sub store_block_files {
295
296 my $self =shift (@_);
297 my ($filename_full_path, $block_hash) = @_;
298
299}
300
301# put files to block into hash
302sub use_block_expressions {
303
304 my $self =shift (@_);
305 my ($filename_full_path, $block_hash) = @_;
306
307 if ($self->{'block_exp'} ne "" && $filename_full_path =~ /$self->{'block_exp'}/) {
308 $block_hash->{'file_blocks'}->{$filename_full_path} = 1;
309 }
310
311}
312
313#default implementation is to block a file with same name as this, but extension jpg or JPG, if cover_images is on.
314sub block_cover_image
315{
316 my $self =shift;
317 my ($filename, $block_hash) = @_;
318
319 if ($self->{'cover_image'}) {
320 my $coverfile = $filename;
321 $coverfile =~ s/\.[^\\\/\.]+$/\.jpg/;
322 if (!-e $coverfile) {
323 $coverfile =~ s/jpg$/JPG/;
324 }
325 if (-e $coverfile) {
326 $block_hash->{'file_blocks'}->{$coverfile} = 1;
327 }
328 }
329
330 return;
331}
332
333
334# discover all the files that should be blocked by this plugin
335# check the args ...
336sub file_block_read {
337
338 my $self = shift (@_);
339 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $gli) = @_;
340 # Keep track of filenames with same root but different extensions
341 # Used to support -associate_ext and the more generalised
342 # -associate_tail_re
343 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
344
345 my $associate_tail_re = $self->{'associate_tail_re'};
346 if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
347
348 my ($file_prefix,$file_ext)
349 = &util::get_prefix_and_tail_by_regex($filename_full_path,$associate_tail_re);
350
351 if ((defined $file_prefix) && (defined $file_ext)) {
352 my $shared_fileroot = $block_hash->{'shared_fileroot'};
353 if (!defined $shared_fileroot->{$file_prefix}) {
354 my $file_prefix_rec = { 'tie_to' => undef,
355 'exts' => {} };
356 $shared_fileroot->{$file_prefix} = $file_prefix_rec;
357 }
358
359 my $file_prefix_rec = $shared_fileroot->{$file_prefix};
360
361 if ($self->can_process_this_file($filename_full_path)) {
362 # This is the document the others should be tied to
363 $file_prefix_rec->{'tie_to'} = $file_ext;
364 }
365 else {
366 if ($file_ext =~ m/$associate_tail_re$/) {
367 # this file should be associated to the main one
368 $file_prefix_rec->{'exts'}->{$file_ext} = 1;
369 }
370 }
371
372 }
373 }
374
375 # check block expressions
376 $self->use_block_expressions($filename_full_path, $block_hash) unless $self->{'no_blocking'};
377
378 # now check whether we are actually processing this
379 if (!-f $filename_full_path || !$self->can_process_this_file($filename_full_path)) {
380 return undef; # can't recognise
381 }
382
383 $self->store_block_files($filename_full_path, $block_hash) unless $self->{'no_blocking'};
384
385 # block the cover image if there is one
386 if ($self->{'cover_image'}) {
387 $self->block_cover_image($filename_full_path, $block_hash) unless $self->{'no_blocking'};
388 }
389
390 return 1;
391}
392
393# plugins that rely on more than process_exp (eg XML plugins) can override this method
394sub can_process_this_file {
395 my $self = shift(@_);
396 my ($filename) = @_;
397
398 if ($self->{'process_exp'} ne "" && $filename =~ /$self->{'process_exp'}/) {
399 return 1;
400 }
401 return 0;
402
403}
404
405# just converts path as is to utf8.
406sub filepath_to_utf8 {
407 my $self = shift (@_);
408 my ($file, $file_encoding) = @_;
409 my $filemeta = $file;
410
411 my $filename_encoding = $self->{'filename_encoding'}; # filename encoding setting
412
413## print STDERR "**** User chose filename encoding setting: $filename_encoding\n";
414
415 # Whenever filename-encoding is set to any of the auto settings, we
416 # check if the filename is already in UTF8. If it is, then we're done.
417 if($filename_encoding =~ m/auto/) {
418 if(&unicode::check_is_utf8($filemeta))
419 {
420## print STDERR "**** It is already UTF8\n";
421 $filename_encoding = "utf8";
422 return $filemeta;
423 }
424 }
425
426 # Auto setting, but filename is not utf8
427 if ($filename_encoding eq "auto")
428 {
429 # try textcat
430 $filename_encoding = $self->textcat_encoding($filemeta);
431
432 # check the locale next
433 $filename_encoding = $self->locale_encoding() if $filename_encoding eq "undefined";
434
435
436 # now try the encoding of the document, if available
437 if ($filename_encoding eq "undefined" && defined $file_encoding) {
438 $filename_encoding = $file_encoding;
439 }
440
441 }
442
443 elsif ($filename_encoding eq "auto-language-analysis")
444 {
445 $filename_encoding = $self->textcat_encoding($filemeta);
446
447 # now try the encoding of the document, if available
448 if ($filename_encoding eq "undefined" && defined $file_encoding) {
449 $filename_encoding = $file_encoding;
450 }
451 }
452
453 elsif ($filename_encoding eq "auto-filesystem-encoding")
454 {
455 # try locale
456 $filename_encoding = $self->locale_encoding();
457 }
458
459 elsif ($filename_encoding eq "auto-fl")
460 {
461 # filesystem-encoding (locale) then language-analysis (textcat)
462 $filename_encoding = $self->locale_encoding();
463
464 # try textcat
465 $filename_encoding = $self->textcat_encoding($filemeta) if $filename_encoding eq "undefined";
466
467 # else assume filename encoding is encoding of file content, if that's available
468 if ($filename_encoding eq "undefined" && defined $file_encoding) {
469 $filename_encoding = $file_encoding;
470 }
471 }
472
473 elsif ($filename_encoding eq "auto-lf")
474 {
475 # language-analysis (textcat) then filesystem-encoding (locale)
476 $filename_encoding = $self->textcat_encoding($filemeta);
477
478 # guess filename encoding from encoding of file content, if available
479 if ($filename_encoding eq "undefined" && defined $file_encoding) {
480 $filename_encoding = $file_encoding;
481 }
482
483 # try locale
484 $filename_encoding = $self->locale_encoding() if $filename_encoding eq "undefined";
485 }
486
487## print STDERR "**** filename_encoding selected: $filename_encoding \n";
488
489 # if still undefined, use utf8 as fallback
490 if ($filename_encoding eq "undefined") {
491 $filename_encoding = "utf8";
492 }
493
494 # if the filename encoding is set to utf8 but it isn't utf8 already--such as when
495 # 1. the utf8 fallback is used, or 2. if the system locale is used and happens to
496 # be always utf8 (in which case the filename's encoding is also set as utf8 even
497 # though the filename need not be if it originates from another system)--in such
498 # cases attempt to make the filename utf8 to match.
499 if($filename_encoding eq "utf8" && !&unicode::check_is_utf8($filemeta)) {
500## print STDERR "**** BEFORE utf8 conversion: $filemeta\n";
501 &unicode::ensure_utf8(\$filemeta);
502## print STDERR "**** AFTER utf8 conversion: $filemeta\n";
503 }
504
505
506 # convert non-unicode encodings to utf8
507 if ($filename_encoding !~ m/(?:ascii|utf8|unicode)/) {
508 $filemeta = &unicode::unicode2utf8(
509 &unicode::convert2unicode($filename_encoding, \$filemeta)
510 );
511 }
512
513 print "*** filename encoding found: $filename_encoding\n";
514 print "*** utf8 encoded filename: $filemeta\n";
515
516 return $filemeta;
517}
518
519# gets the filename with no path, converts to utf8, and then dm safes it.
520#filename_encoding set by user
521sub filename_to_utf8_metadata
522{
523 my $self = shift (@_);
524 my ($file, $file_encoding) = @_;
525
526 my $outhandle = $self->{'outhandle'};
527
528 my ($filemeta) = $file =~ /([^\\\/]+)$/; # getting the tail of the filepath (skips all string parts containing slashes upto the end)
529 $filemeta = $self->filepath_to_utf8($filemeta, $file_encoding);
530
531 my $dmsafe_filemeta = &ghtml::dmsafe($filemeta);
532
533 return $dmsafe_filemeta;
534
535}
536
537sub locale_encoding {
538 my $self = shift(@_);
539
540 if (!defined $self->{'filesystem_encoding'}) {
541 $self->{'filesystem_encoding'} = $self->get_filesystem_encoding();
542 $self->{'filesystem_encoding'} = "undefined" if !defined $self->{'filesystem_encoding'};
543 }
544
545 print "filename encoding determined based on locale: " . $self->{'filesystem_encoding'} . "\n";
546 return $self->{'filesystem_encoding'}; # can be the string "undefined"
547}
548
549sub textcat_encoding {
550 my $self = shift(@_);
551 my ($filemeta) = @_;
552
553 # analyse filenames without extensions and digits (and trimmed of surrounding
554 # whitespace), so that irrelevant chars don't confuse textcat
555 my $strictfilemeta = $filemeta;
556 $strictfilemeta =~ s/\.[^\.]+$//g;
557 $strictfilemeta =~ s/\d//g;
558 $strictfilemeta =~ s/^\s*//g;
559 $strictfilemeta =~ s/\s*$//g;
560
561## print STDERR "**** strict filename is |$strictfilemeta|\n";
562 my $filename_encoding = $self->encoding_from_language_analysis($strictfilemeta);
563 if(!defined $filename_encoding) {
564 $filename_encoding = "undefined";
565 }
566
567## print STDERR "**** textcat found filename encoding: " . $file_textcat_encoding_map{$strictfilemeta} . "\n";
568 return $filename_encoding; # can be the string "undefined"
569}
570
571# performs textcat
572sub encoding_from_language_analysis {
573 my $self = shift(@_);
574 my ($text) = @_;
575
576 my $outhandle = $self->{'outhandle'};
577 my $best_encoding = undef;
578
579 # get the language/encoding of the file using textcat
580 $self->{'textcat'} = new textcat() unless defined($self->{'textcat'});
581 #my $results = $self->{'textcat'}->classify(\$text);
582 my $results = $self->{'textcat'}->classify_cached(\$text);
583
584
585 if (scalar @$results < 0) {
586 print STDERR "**** Textcat returned 0 results\n";
587 return undef;
588 }
589
590 print STDERR "**** TEXTCAT RESULTS for $text: ";
591 print STDERR join(",", @$results);
592 print STDERR "\n";
593
594 # We have some results, we choose the first
595 my ($language, $encoding) = $results->[0] =~ /^([^-]*)(?:-(.*))?$/;
596
597 $best_encoding = $encoding;
598 if (!defined $best_encoding) {
599## print STDERR "**** Textcat cannot determine encoding of filename: it's undefined.\n";
600 return undef;
601 }
602
603 if (defined $best_encoding && $best_encoding =~ m/^iso_8859/ && &unicode::check_is_utf8($text)) {
604 # the text is valid utf8, so assume that's the real encoding (since textcat is based on probabilities)
605## print STDERR "*** Filename turns out to be UTF8\n";
606 $best_encoding = 'utf8';
607 }
608
609
610 # check for equivalents where textcat doesn't have some encodings...
611 # eg MS versions of standard encodings
612 if (defined $best_encoding && $best_encoding =~ /^iso_8859_(\d+)/) {
613## print STDERR "**** best_encoding is ISO_8859: $best_encoding\n";
614
615 my $iso = $1; # which variant of the iso standard?
616 # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
617 if ($text =~ /[\x80-\x9f]/) {
618## print STDERR "**** best_encoding is some windows value: $best_encoding\n";
619 # Western Europe
620 if ($iso == 1 or $iso == 15) { $best_encoding = 'windows_1252' }
621 elsif ($iso == 2) {$best_encoding = 'windows_1250'} # Central Europe
622 elsif ($iso == 5) {$best_encoding = 'windows_1251'} # Cyrillic
623 elsif ($iso == 6) {$best_encoding = 'windows_1256'} # Arabic
624 elsif ($iso == 7) {$best_encoding = 'windows_1253'} # Greek
625 elsif ($iso == 8) {$best_encoding = 'windows_1255'} # Hebrew
626 elsif ($iso == 9) {$best_encoding = 'windows_1254'} # Turkish
627## print STDERR "**** best_encoding windows value: $best_encoding\n";
628 }
629 }
630
631 if (defined $best_encoding && $best_encoding !~ /^(ascii|utf8|unicode)$/ &&
632 !defined $encodings::encodings->{$best_encoding})
633 {
634 if ($self->{'verbosity'}) {
635 gsprintf($outhandle, "BasePlugin: {ReadTextFile.unsupported_encoding}\n", $text, $best_encoding, "undef");
636 }
637## print STDERR "***** unsupported encoding: $best_encoding. Setting it to undefined.\n";
638 $best_encoding = undef;
639 }
640## print STDERR "**** language: $language\n" if defined $language;
641## print STDERR "**** encoding: $best_encoding\n" if defined $encoding;
642
643 return $best_encoding;
644}
645
646# uses locale
647sub get_filesystem_encoding {
648
649 my $self = shift(@_);
650
651 my $outhandle = $self->{'outhandle'};
652 my $filesystem_encoding = undef;
653
654 eval {
655 use POSIX qw(locale_h);
656
657 # With only one parameter, setlocale retrieves the
658 # current value
659 my $current_locale = setlocale(LC_CTYPE);
660
661 if ($current_locale =~ m/^.*\.(.*?)$/) {
662 my $char_encoding = lc($1);
663 if ($char_encoding =~ m/^(iso)(8859)(\d{1,2})$/) {
664 $char_encoding = "$1\_$2\_$3";
665 }
666
667 $char_encoding =~ s/-/_/g;
668 $char_encoding =~ s/^utf_8$/utf8/;
669
670 if ($char_encoding =~ m/^\d+$/) {
671 if (defined $encodings::encodings->{"windows_$char_encoding"}) {
672 $char_encoding = "windows_$char_encoding";
673 }
674 elsif (defined $encodings::encodings->{"dos_$char_encoding"}) {
675 $char_encoding = "dos_$char_encoding";
676 }
677 }
678
679 if (($char_encoding =~ m/(?:ascii|utf8|unicode)/)
680 || (defined $encodings::encodings->{$char_encoding})) {
681 $filesystem_encoding = $char_encoding;
682 }
683 else {
684 print $outhandle "Warning: Unsupported character encoding '$char_encoding' from locale '$current_locale'\n";
685 }
686 }
687
688
689 };
690 if ($@) {
691 print $outhandle "$@\n";
692 print $outhandle "Warning: Unable to establish locale. Will assume filesytem is UTF-8\n";
693
694 }
695 return $filesystem_encoding;
696}
697
698# is there ever only one Source? Sometimes this will be called twice, for images etc that are converted.
699sub set_Source_metadata {
700 my $self = shift (@_);
701 my ($doc_obj, $filename_no_path, $file_encoding) = @_;
702
703 my $top_section = $doc_obj->get_top_section();
704
705 # UTF-8 version of filename
706 my $filemeta = $self->filename_to_utf8_metadata($filename_no_path, $file_encoding);
707 $doc_obj->set_utf8_metadata_element($top_section, "Source", $filemeta);
708
709}
710
711sub add_OID {
712
713 my $self = shift (@_);
714 my ($doc_obj) = @_;
715
716 # See if a metadata field is specified as the field
717 if ((defined $self->{'use_as_doc_identifier'}) && ($self->{'use_as_doc_identifier'} ne "")) {
718 my $metadata_doc_id = $self->{'use_as_doc_identifier'};
719
720 # Consider "tidying" up metadata_doc_id to be something
721 # suitable in a URL
722 # Could even support a user specified plugin RE for this.
723
724 my $top_section = $doc_obj->get_top_section();
725 my $oid = $doc_obj->get_metadata_element($top_section,$metadata_doc_id);
726## print STDERR "**** oid = $oid\n";
727 $doc_obj->set_OID($oid);
728 }
729 # See if there is a plugin-specific set_OID function...
730 elsif (defined ($self->can('set_OID'))) {
731 # it will need $doc_obj to set the Identifier metadata...
732 $self->set_OID(@_); # pass through any extra arguments supplied
733 } else {
734 # use the default set_OID() in doc.pm
735 $doc_obj->set_OID();
736 }
737}
738
739
740
741# The BasePlugin read_into_doc_obj() function. This function does all the
742# right things to make general options work for a given plugin. It doesn't do anything with the file other than setting reads in
743# a file and sets up a slew of metadata all saved in doc_obj, which
744# it then returns as part of a tuple (process_status,doc_obj)
745#
746# Much of this functionality used to reside in read, but it was broken
747# down into a supporting routine to make the code more flexible.
748#
749# recursive plugins (e.g. RecPlug) and specialized plugins like those
750# capable of processing many documents within a single file (e.g.
751# GMLPlug) will normally want to implement their own version of
752# read_into_doc_obj()
753#
754# Note that $base_dir might be "" and that $file might
755# include directories
756
757# currently blocking has been done before it gets here - does this affect secondary plugin stuff??
758sub read_into_doc_obj {
759 my $self = shift (@_);
760 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
761
762 my $outhandle = $self->{'outhandle'};
763
764 # should we move this to read? What about secondary plugins?
765 print STDERR "<Processing n='$file' p='$self->{'plugin_type'}'>\n" if ($gli);
766 print $outhandle "$self->{'plugin_type'} processing $file\n"
767 if $self->{'verbosity'} > 1;
768
769 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
770 # create a new document
771 my $doc_obj = new doc ($filename_full_path, "indexed_doc");
772 my $top_section = $doc_obj->get_top_section();
773
774 # this should look at the plugin option too...
775 $doc_obj->set_OIDtype ($processor->{'OIDtype'}, $processor->{'OIDmetadata'});
776 $doc_obj->add_utf8_metadata($top_section, "Plugin", "$self->{'plugin_type'}");
777 $doc_obj->add_utf8_metadata($top_section, "FileSize", (-s $filename_full_path));
778
779 $self->set_Source_metadata($doc_obj, $filename_no_path);
780
781 # plugin specific stuff - what args do we need here??
782 unless (defined ($self->process($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
783 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
784 return -1;
785 }
786
787 # include any metadata passed in from previous plugins
788 # note that this metadata is associated with the top level section
789 my $section = $doc_obj->get_top_section();
790 # can we merge these two methods??
791 $self->add_associated_files($doc_obj, $filename_full_path);
792 $self->extra_metadata ($doc_obj, $section, $metadata);
793 $self->auto_extract_metadata($doc_obj);
794
795 # if we haven't found any Title so far, assign one
796 # this was shifted to here from inside read()
797 $self->title_fallback($doc_obj,$section,$filename_no_path);
798
799 $self->add_OID($doc_obj);
800
801 return (1,$doc_obj);
802}
803
804sub add_dummy_text {
805 my $self = shift(@_);
806 my ($doc_obj, $section) = @_;
807
808 # add NoText metadata so we can hide this dummy text in format statements
809 $doc_obj->add_metadata($section, "NoText", "1");
810 $doc_obj->add_text($section, &gsprintf::lookup_string("{BasePlugin.dummy_text}",1));
811
812}
813
814# does nothing. Can be overridden by subclass
815sub auto_extract_metadata {
816 my $self = shift(@_);
817 my ($doc_obj) = @_;
818}
819
820# adds cover image, associate_file options stuff. Should be called by sub class
821# read_into_doc_obj
822sub add_associated_files {
823 my $self = shift(@_);
824 # whatis filename??
825 my ($doc_obj, $filename) = @_;
826
827 # add in the cover image
828 if ($self->{'cover_image'}) {
829 $self->associate_cover_image($doc_obj, $filename);
830 }
831
832
833}
834
835# implement this if you are extracting metadata for other documents
836sub metadata_read {
837 my $self = shift (@_);
838 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $extrametakeys, $extrametadata, $processor, $maxdocs, $gli) = @_;
839
840 # can we process this file??
841 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
842 return undef unless $self->can_process_this_file($filename_full_path);
843
844 return 1; # we recognise the file, but don't actually do anything with it
845}
846
847
848# The BasePlugin read() function. This function calls read_into_doc_obj()
849# to ensure all the right things to make general options work for a
850# given plugin are done. It then calls the process() function which
851# does all the work specific to a plugin (like the old read functions
852# used to do). Most plugins should define their own process() function
853# and let this read() function keep control.
854#
855# recursive plugins (e.g. RecPlug) and specialized plugins like those
856# capable of processing many documents within a single file (e.g.
857# GMLPlug) might want to implement their own version of read(), but
858# more likely need to implement their own version of read_into_doc_obj()
859#
860# Return number of files processed, undef if can't recognise, -1 if can't
861# process
862
863sub read {
864 my $self = shift (@_);
865 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
866
867 # can we process this file??
868 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
869 return undef unless $self->can_process_this_file($filename_full_path);
870
871 my ($process_status,$doc_obj) = $self->read_into_doc_obj(@_);
872
873 if ((defined $process_status) && ($process_status == 1)) {
874
875 # process the document
876 $processor->process($doc_obj);
877
878 $self->{'num_processed'} ++;
879 undef $doc_obj;
880 }
881 # delete any temp files that we may have created
882 $self->clean_up_after_doc_obj_processing();
883
884 # if process_status == 1, then the file has been processed.
885 return $process_status;
886
887}
888
889# returns undef if file is rejected by the plugin
890sub process {
891 my $self = shift (@_);
892 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
893
894 gsprintf(STDERR, "BasePlugin::process {common.must_be_implemented}\n") && die "\n";
895
896 return undef; # never gets here
897}
898
899# overwrite this method to delete any temp files that we have created
900sub clean_up_after_doc_obj_processing {
901 my $self = shift(@_);
902
903}
904
905# write_file -- used by ConvertToPlug, for example in post processing
906#
907# where should this go, is here the best place??
908sub utf8_write_file {
909 my $self = shift (@_);
910 my ($textref, $filename) = @_;
911
912 if (!open (FILE, ">$filename")) {
913 gsprintf(STDERR, "ConvertToPlug::write_file {ConvertToPlug.could_not_open_for_writing} ($!)\n", $filename);
914 die "\n";
915 }
916 print FILE $$textref;
917
918 close FILE;
919}
920
921
922sub filename_based_title
923{
924 my $self = shift (@_);
925 my ($file) = @_;
926
927 my $file_derived_title = $file;
928 $file_derived_title =~ s/_/ /g;
929 $file_derived_title =~ s/\..*?$//;
930
931 return $file_derived_title;
932}
933
934
935sub title_fallback
936{
937 my $self = shift (@_);
938 my ($doc_obj,$section,$file) = @_;
939
940 if (!defined $doc_obj->get_metadata_element ($section, "Title") or $doc_obj->get_metadata_element($section, "Title") eq "") {
941
942 my $file_derived_title = $self->filename_to_utf8_metadata($self->filename_based_title($file));
943 if (!defined $doc_obj->get_metadata_element ($section, "Title")) {
944 $doc_obj->add_utf8_metadata ($section, "Title", $file_derived_title);
945 }
946 else {
947 $doc_obj->set_utf8_metadata ($section, "Title", $file_derived_title);
948 }
949 }
950
951}
952
953# add any extra metadata that's been passed around from one
954# plugin to another.
955# extra_metadata uses add_utf8_metadata so it expects metadata values
956# to already be in utf8
957sub extra_metadata {
958 my $self = shift (@_);
959 my ($doc_obj, $cursection, $metadata) = @_;
960
961 my $associate_tail_re = $self->{'associate_tail_re'};
962
963 foreach my $field (keys(%$metadata)) {
964 # $metadata->{$field} may be an array reference
965 if ($field eq "gsdlassocfile_tobe") {
966 # 'gsdlassocfile_tobe' is artificially introduced metadata
967 # that is used to signal that certain additional files should
968 # be tied to this document. Useful in situations where a
969 # metadata pass in the plugin pipeline works out some files
970 # need to be associated with a document, but the document hasn't
971 # been formed yet.
972 my $equiv_form = "";
973 foreach my $gaf (@{$metadata->{$field}}) {
974 my ($full_filename,$mimetype) = ($gaf =~ m/^(.*):(.*):$/);
975 my ($tail_filename) = ($full_filename =~ /^.*[\/\\](.+?)$/);
976 my $filename = $full_filename;
977 $doc_obj->associate_file($full_filename,$tail_filename,$mimetype);
978
979 # work out extended tail extension (i.e. matching tail re)
980
981 my ($file_prefix,$file_extended_ext)
982 = &util::get_prefix_and_tail_by_regex($tail_filename,$associate_tail_re);
983 my ($pre_doc_ext) = ($file_extended_ext =~ m/^(.*)\..*$/);
984
985 my ($doc_ext) = ($tail_filename =~ m/^.*\.(.*)$/);
986 my $start_doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/{Or}{[parent(Top):archivedir],[archivedir]}/$tail_filename\">";
987 my $srcicon = "_icon".$doc_ext."_";
988 my $end_doclink = "</a>";
989
990 my $assoc_form = "$start_doclink\{If\}{$srcicon,$srcicon,$doc_ext\}$end_doclink";
991
992 if (defined $pre_doc_ext) {
993 # for metadata such as [mp3._edited] [mp3._full] ...
994 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.$pre_doc_ext", $assoc_form);
995 }
996
997 # for multiple metadata such as [mp3.assoclink]
998 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.assoclink", $assoc_form);
999
1000 $equiv_form .= " $assoc_form";
1001 }
1002 $doc_obj->add_utf8_metadata ($cursection, "equivlink", $equiv_form);
1003 }
1004 elsif (ref ($metadata->{$field}) eq "ARRAY") {
1005 map {
1006 $doc_obj->add_utf8_metadata ($cursection, $field, $_);
1007 } @{$metadata->{$field}};
1008 } else {
1009 $doc_obj->add_utf8_metadata ($cursection, $field, $metadata->{$field});
1010 }
1011 }
1012}
1013
1014
1015sub compile_stats {
1016 my $self = shift(@_);
1017 my ($stats) = @_;
1018
1019 $stats->{'num_processed'} += $self->{'num_processed'};
1020 $stats->{'num_not_processed'} += $self->{'num_not_processed'};
1021 $stats->{'num_archives'} += $self->{'num_archives'};
1022
1023}
1024
1025sub associate_cover_image {
1026 my $self = shift;
1027 my ($doc_obj, $filename) = @_;
1028
1029 $filename =~ s/\.[^\\\/\.]+$/\.jpg/;
1030 if (exists $self->{'covers_missing_cache'}->{$filename}) {
1031 # don't stat() for existence eg for multiple document input files
1032 # (eg SplitPlug)
1033 return;
1034 }
1035
1036 my $top_section=$doc_obj->get_top_section();
1037
1038 if (-e $filename) {
1039 $doc_obj->associate_file($filename, "cover.jpg", "image/jpeg");
1040 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1041 } else {
1042 my $upper_filename = $filename;
1043 $upper_filename =~ s/jpg$/JPG/;
1044 if (-e $upper_filename) {
1045 $doc_obj->associate_file($upper_filename, "cover.jpg",
1046 "image/jpeg");
1047 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1048 } else {
1049 # file doesn't exist, so record the fact that it's missing so
1050 # we don't stat() again (stat is slow)
1051 $self->{'covers_missing_cache'}->{$filename} = 1;
1052 }
1053 }
1054
1055}
1056
1057
1058# Overridden by exploding plugins (eg. ISISPlug)
1059sub clean_up_after_exploding
1060{
1061 my $self = shift(@_);
1062}
1063
1064
1065
10661;
Note: See TracBrowser for help on using the repository browser.