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

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

Introduced new merge_inheritance function, useful in a plugin constructor where it is known that later methods will access fields from *multiple* $self super-classes created in the constructor

  • Property svn:keywords set to Author Date Id Revision
File size: 32.9 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
216sub merge_inheritance
217{
218 my $self = {};
219 my @child_selfs = @_;
220
221 foreach my $child_self (@child_selfs) {
222 foreach my $key (keys %$child_self) {
223 if (defined $self->{$key}) {
224 if ($self->{$key} ne $child_self->{$key}) {
225# print STDERR "Warning: Conflicting value in multiple inheritance for '$key'\n";
226# print STDERR "Existing stored value = $self->{$key}\n";
227# print STDERR "New (child) value = $child_self->{$key}\n";
228# print STDERR "Keeping existing value\n";
229 # Existing value seems to be option specified in collect.cfg
230
231 ### $self->{$key} = $child_self->{$key};
232
233 }
234 else {
235## print STDERR "****Info: Value $self->{$key} for $key already defined through multiple inheritance as the same value\n";
236 }
237
238 }
239 else {
240 $self->{$key} = $child_self->{$key};
241 }
242 }
243 }
244
245 return $self;
246}
247
248# initialize BasePlugin options
249# if init() is overridden in a sub-class, remember to call BasePlugin::init()
250sub init {
251 my $self = shift (@_);
252 my ($verbosity, $outhandle, $failhandle) = @_;
253
254 # verbosity is passed through from the processor
255 $self->{'verbosity'} = $verbosity;
256
257 # as are the outhandle and failhandle
258 $self->{'outhandle'} = $outhandle if defined $outhandle;
259 $self->{'failhandle'} = $failhandle;
260# $self->SUPER::init(@_);
261
262 # set process_exp and block_exp to defaults unless they were
263 # explicitly set
264
265 if ((!$self->is_recursive()) and
266 (!defined $self->{'process_exp'}) || ($self->{'process_exp'} eq "")) {
267
268 $self->{'process_exp'} = $self->get_default_process_exp ();
269 if ($self->{'process_exp'} eq "") {
270 warn ref($self) . " Warning: Non-recursive plugin has no process_exp\n";
271 }
272 }
273
274 if ((!defined $self->{'block_exp'}) || ($self->{'block_exp'} eq "")) {
275 $self->{'block_exp'} = $self->get_default_block_exp ();
276 }
277
278}
279
280sub begin {
281 my $self = shift (@_);
282 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
283
284 # Save base_dir for use in file cache
285 # Would be more logical to do this in MediaConverter, but
286 # it's begin method doesn't appear to be called (29/6/08)
287 $self->{'base_dir'} = $base_dir;
288}
289
290sub end {
291 # potentially called at the end of each plugin pass
292 # import.pl only has one plugin pass, but buildcol.pl has multiple ones
293
294 my ($self) = shift (@_);
295}
296
297sub deinit {
298 # called only once, after all plugin passes have been done
299
300 my ($self) = @_;
301}
302
303sub set_incremental {
304 my $self = shift(@_);
305 my ($incremental) = @_;
306
307 $self->{'incremental'} = $incremental;
308}
309
310# this function should be overridden to return 1
311# in recursive plugins
312sub is_recursive {
313 my $self = shift (@_);
314
315 return 0;
316}
317
318sub get_default_block_exp {
319 my $self = shift (@_);
320
321 return "";
322}
323
324sub get_default_process_exp {
325 my $self = shift (@_);
326
327 return "";
328}
329
330# default implementation is to do nothing
331sub store_block_files {
332
333 my $self =shift (@_);
334 my ($filename_full_path, $block_hash) = @_;
335
336}
337
338# put files to block into hash
339sub use_block_expressions {
340
341 my $self =shift (@_);
342 my ($filename_full_path, $block_hash) = @_;
343
344 if ($self->{'block_exp'} ne "" && $filename_full_path =~ /$self->{'block_exp'}/) {
345 $block_hash->{'file_blocks'}->{$filename_full_path} = 1;
346 }
347
348}
349
350#default implementation is to block a file with same name as this, but extension jpg or JPG, if cover_images is on.
351sub block_cover_image
352{
353 my $self =shift;
354 my ($filename, $block_hash) = @_;
355
356 if ($self->{'cover_image'}) {
357 my $coverfile = $filename;
358 $coverfile =~ s/\.[^\\\/\.]+$/\.jpg/;
359 if (!-e $coverfile) {
360 $coverfile =~ s/jpg$/JPG/;
361 }
362 if (-e $coverfile) {
363 $block_hash->{'file_blocks'}->{$coverfile} = 1;
364 }
365 }
366
367 return;
368}
369
370
371# discover all the files that should be blocked by this plugin
372# check the args ...
373sub file_block_read {
374
375 my $self = shift (@_);
376 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $gli) = @_;
377 # Keep track of filenames with same root but different extensions
378 # Used to support -associate_ext and the more generalised
379 # -associate_tail_re
380 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
381
382 my $associate_tail_re = $self->{'associate_tail_re'};
383 if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
384
385 my ($file_prefix,$file_ext)
386 = &util::get_prefix_and_tail_by_regex($filename_full_path,$associate_tail_re);
387
388 if ((defined $file_prefix) && (defined $file_ext)) {
389 my $shared_fileroot = $block_hash->{'shared_fileroot'};
390 if (!defined $shared_fileroot->{$file_prefix}) {
391 my $file_prefix_rec = { 'tie_to' => undef,
392 'exts' => {} };
393 $shared_fileroot->{$file_prefix} = $file_prefix_rec;
394 }
395
396 my $file_prefix_rec = $shared_fileroot->{$file_prefix};
397
398 if ($self->can_process_this_file($filename_full_path)) {
399 # This is the document the others should be tied to
400 $file_prefix_rec->{'tie_to'} = $file_ext;
401 }
402 else {
403 if ($file_ext =~ m/$associate_tail_re$/) {
404 # this file should be associated to the main one
405 $file_prefix_rec->{'exts'}->{$file_ext} = 1;
406 }
407 }
408
409 }
410 }
411
412 # check block expressions
413 $self->use_block_expressions($filename_full_path, $block_hash) unless $self->{'no_blocking'};
414
415 # now check whether we are actually processing this
416 if (!-f $filename_full_path || !$self->can_process_this_file($filename_full_path)) {
417 return undef; # can't recognise
418 }
419
420 $self->store_block_files($filename_full_path, $block_hash) unless $self->{'no_blocking'};
421
422 # block the cover image if there is one
423 if ($self->{'cover_image'}) {
424 $self->block_cover_image($filename_full_path, $block_hash) unless $self->{'no_blocking'};
425 }
426
427 return 1;
428}
429
430# plugins that rely on more than process_exp (eg XML plugins) can override this method
431sub can_process_this_file {
432 my $self = shift(@_);
433 my ($filename) = @_;
434
435 if ($self->{'process_exp'} ne "" && $filename =~ /$self->{'process_exp'}/) {
436 return 1;
437 }
438 return 0;
439
440}
441
442# just converts path as is to utf8.
443sub filepath_to_utf8 {
444 my $self = shift (@_);
445 my ($file, $file_encoding) = @_;
446 my $filemeta = $file;
447
448 my $filename_encoding = $self->{'filename_encoding'}; # filename encoding setting
449
450 # Whenever filename-encoding is set to any of the auto settings, we
451 # check if the filename is already in UTF8. If it is, then we're done.
452 if($filename_encoding =~ m/auto/) {
453 if(&unicode::check_is_utf8($filemeta))
454 {
455 $filename_encoding = "utf8";
456 return $filemeta;
457 }
458 }
459
460 # Auto setting, but filename is not utf8
461 if ($filename_encoding eq "auto")
462 {
463 # try textcat
464 $filename_encoding = $self->textcat_encoding($filemeta);
465
466 # check the locale next
467 $filename_encoding = $self->locale_encoding() if $filename_encoding eq "undefined";
468
469
470 # now try the encoding of the document, if available
471 if ($filename_encoding eq "undefined" && defined $file_encoding) {
472 $filename_encoding = $file_encoding;
473 }
474
475 }
476
477 elsif ($filename_encoding eq "auto-language-analysis")
478 {
479 $filename_encoding = $self->textcat_encoding($filemeta);
480
481 # now try the encoding of the document, if available
482 if ($filename_encoding eq "undefined" && defined $file_encoding) {
483 $filename_encoding = $file_encoding;
484 }
485 }
486
487 elsif ($filename_encoding eq "auto-filesystem-encoding")
488 {
489 # try locale
490 $filename_encoding = $self->locale_encoding();
491 }
492
493 elsif ($filename_encoding eq "auto-fl")
494 {
495 # filesystem-encoding (locale) then language-analysis (textcat)
496 $filename_encoding = $self->locale_encoding();
497
498 # try textcat
499 $filename_encoding = $self->textcat_encoding($filemeta) if $filename_encoding eq "undefined";
500
501 # else assume filename encoding is encoding of file content, if that's available
502 if ($filename_encoding eq "undefined" && defined $file_encoding) {
503 $filename_encoding = $file_encoding;
504 }
505 }
506
507 elsif ($filename_encoding eq "auto-lf")
508 {
509 # language-analysis (textcat) then filesystem-encoding (locale)
510 $filename_encoding = $self->textcat_encoding($filemeta);
511
512 # guess filename encoding from encoding of file content, if available
513 if ($filename_encoding eq "undefined" && defined $file_encoding) {
514 $filename_encoding = $file_encoding;
515 }
516
517 # try locale
518 $filename_encoding = $self->locale_encoding() if $filename_encoding eq "undefined";
519 }
520
521 # if still undefined, use utf8 as fallback
522 if ($filename_encoding eq "undefined") {
523 $filename_encoding = "utf8";
524 }
525
526 print STDERR "**** UTF8 encoding the filename $filemeta ";
527
528 # if the filename encoding is set to utf8 but it isn't utf8 already--such as when
529 # 1. the utf8 fallback is used, or 2. if the system locale is used and happens to
530 # be always utf8 (in which case the filename's encoding is also set as utf8 even
531 # though the filename need not be if it originates from another system)--in such
532 # cases attempt to make the filename utf8 to match.
533 if($filename_encoding eq "utf8" && !&unicode::check_is_utf8($filemeta)) {
534 &unicode::ensure_utf8(\$filemeta);
535 }
536
537 # convert non-unicode encodings to utf8
538 if ($filename_encoding !~ m/(?:ascii|utf8|unicode)/) {
539 $filemeta = &unicode::unicode2utf8(
540 &unicode::convert2unicode($filename_encoding, \$filemeta)
541 );
542 }
543
544 print STDERR " from encoding $filename_encoding -> $filemeta\n";
545 return $filemeta;
546}
547
548# gets the filename with no path, converts to utf8, and then dm safes it.
549#filename_encoding set by user
550sub filename_to_utf8_metadata
551{
552 my $self = shift (@_);
553 my ($file, $file_encoding) = @_;
554
555 my $outhandle = $self->{'outhandle'};
556
557 my ($filemeta) = $file =~ /([^\\\/]+)$/; # getting the tail of the filepath (skips all string parts containing slashes upto the end)
558 $filemeta = $self->filepath_to_utf8($filemeta, $file_encoding);
559
560 my $dmsafe_filemeta = &ghtml::dmsafe($filemeta);
561
562 return $dmsafe_filemeta;
563
564}
565
566sub locale_encoding {
567 my $self = shift(@_);
568
569 if (!defined $self->{'filesystem_encoding'}) {
570 $self->{'filesystem_encoding'} = $self->get_filesystem_encoding();
571 $self->{'filesystem_encoding'} = "undefined" if !defined $self->{'filesystem_encoding'};
572 }
573
574 print STDERR "*** filename encoding determined based on locale: " . $self->{'filesystem_encoding'} . "\n";
575 return $self->{'filesystem_encoding'}; # can be the string "undefined"
576}
577
578sub textcat_encoding {
579 my $self = shift(@_);
580 my ($filemeta) = @_;
581
582 # analyse filenames without extensions and digits (and trimmed of surrounding
583 # whitespace), so that irrelevant chars don't confuse textcat
584 my $strictfilemeta = $filemeta;
585 $strictfilemeta =~ s/\.[^\.]+$//g;
586 $strictfilemeta =~ s/\d//g;
587 $strictfilemeta =~ s/^\s*//g;
588 $strictfilemeta =~ s/\s*$//g;
589
590 my $filename_encoding = $self->encoding_from_language_analysis($strictfilemeta);
591 if(!defined $filename_encoding) {
592 $filename_encoding = "undefined";
593 }
594
595 return $filename_encoding; # can be the string "undefined"
596}
597
598# performs textcat
599sub encoding_from_language_analysis {
600 my $self = shift(@_);
601 my ($text) = @_;
602
603 my $outhandle = $self->{'outhandle'};
604 my $best_encoding = undef;
605
606 # get the language/encoding of the file using textcat
607 $self->{'textcat'} = new textcat() unless defined($self->{'textcat'});
608 #my $results = $self->{'textcat'}->classify(\$text);
609 my $results = $self->{'textcat'}->classify_cached_filename(\$text);
610
611
612 if (scalar @$results < 0) {
613 return undef;
614 }
615
616## print STDERR "**** TEXTCAT RESULTS for $text: ";
617## print STDERR join(",", @$results);
618## print STDERR "\n";
619
620 # We have some results, we choose the first
621 my ($language, $encoding) = $results->[0] =~ /^([^-]*)(?:-(.*))?$/;
622
623 $best_encoding = $encoding;
624 if (!defined $best_encoding) {
625 return undef;
626 }
627
628 if (defined $best_encoding && $best_encoding =~ m/^iso_8859/ && &unicode::check_is_utf8($text)) {
629 # the text is valid utf8, so assume that's the real encoding (since textcat is based on probabilities)
630 $best_encoding = 'utf8';
631 }
632
633
634 # check for equivalents where textcat doesn't have some encodings...
635 # eg MS versions of standard encodings
636 if (defined $best_encoding && $best_encoding =~ /^iso_8859_(\d+)/) {
637 my $iso = $1; # which variant of the iso standard?
638 # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
639 if ($text =~ /[\x80-\x9f]/) {
640 # Western Europe
641 if ($iso == 1 or $iso == 15) { $best_encoding = 'windows_1252' }
642 elsif ($iso == 2) {$best_encoding = 'windows_1250'} # Central Europe
643 elsif ($iso == 5) {$best_encoding = 'windows_1251'} # Cyrillic
644 elsif ($iso == 6) {$best_encoding = 'windows_1256'} # Arabic
645 elsif ($iso == 7) {$best_encoding = 'windows_1253'} # Greek
646 elsif ($iso == 8) {$best_encoding = 'windows_1255'} # Hebrew
647 elsif ($iso == 9) {$best_encoding = 'windows_1254'} # Turkish
648 }
649 }
650
651 if (defined $best_encoding && $best_encoding !~ /^(ascii|utf8|unicode)$/ &&
652 !defined $encodings::encodings->{$best_encoding})
653 {
654 if ($self->{'verbosity'}) {
655 gsprintf($outhandle, "BasePlugin: {ReadTextFile.unsupported_encoding}\n", $text, $best_encoding, "undef");
656 }
657 $best_encoding = undef;
658 }
659
660 return $best_encoding;
661}
662
663# uses locale
664sub get_filesystem_encoding {
665
666 my $self = shift(@_);
667
668 my $outhandle = $self->{'outhandle'};
669 my $filesystem_encoding = undef;
670
671 eval {
672 use POSIX qw(locale_h);
673
674 # With only one parameter, setlocale retrieves the
675 # current value
676 my $current_locale = setlocale(LC_CTYPE);
677
678 if ($current_locale =~ m/^.*\.(.*?)$/) {
679 my $char_encoding = lc($1);
680 if ($char_encoding =~ m/^(iso)(8859)(\d{1,2})$/) {
681 $char_encoding = "$1\_$2\_$3";
682 }
683
684 $char_encoding =~ s/-/_/g;
685 $char_encoding =~ s/^utf_8$/utf8/;
686
687 if ($char_encoding =~ m/^\d+$/) {
688 if (defined $encodings::encodings->{"windows_$char_encoding"}) {
689 $char_encoding = "windows_$char_encoding";
690 }
691 elsif (defined $encodings::encodings->{"dos_$char_encoding"}) {
692 $char_encoding = "dos_$char_encoding";
693 }
694 }
695
696 if (($char_encoding =~ m/(?:ascii|utf8|unicode)/)
697 || (defined $encodings::encodings->{$char_encoding})) {
698 $filesystem_encoding = $char_encoding;
699 }
700 else {
701 print $outhandle "Warning: Unsupported character encoding '$char_encoding' from locale '$current_locale'\n";
702 }
703 }
704
705
706 };
707 if ($@) {
708 print $outhandle "$@\n";
709 print $outhandle "Warning: Unable to establish locale. Will assume filesytem is UTF-8\n";
710
711 }
712 return $filesystem_encoding;
713}
714
715# is there ever only one Source? Sometimes this will be called twice, for images etc that are converted.
716sub set_Source_metadata {
717 my $self = shift (@_);
718 my ($doc_obj, $filename_no_path, $file_encoding) = @_;
719
720 my $top_section = $doc_obj->get_top_section();
721
722 # UTF-8 version of filename
723 my $filemeta = $self->filename_to_utf8_metadata($filename_no_path, $file_encoding);
724 $doc_obj->set_utf8_metadata_element($top_section, "Source", $filemeta);
725}
726
727sub add_OID {
728
729 my $self = shift (@_);
730 my ($doc_obj) = @_;
731
732 # See if a metadata field is specified as the field
733 if ((defined $self->{'use_as_doc_identifier'}) && ($self->{'use_as_doc_identifier'} ne "")) {
734 my $metadata_doc_id = $self->{'use_as_doc_identifier'};
735
736 # Consider "tidying" up metadata_doc_id to be something
737 # suitable in a URL
738 # Could even support a user specified plugin RE for this.
739
740 my $top_section = $doc_obj->get_top_section();
741 my $oid = $doc_obj->get_metadata_element($top_section,$metadata_doc_id);
742 $doc_obj->set_OID($oid);
743 }
744 # See if there is a plugin-specific set_OID function...
745 elsif (defined ($self->can('set_OID'))) {
746 # it will need $doc_obj to set the Identifier metadata...
747 $self->set_OID(@_); # pass through any extra arguments supplied
748 } else {
749 # use the default set_OID() in doc.pm
750 $doc_obj->set_OID();
751 }
752}
753
754
755
756# The BasePlugin read_into_doc_obj() function. This function does all the
757# right things to make general options work for a given plugin. It doesn't do anything with the file other than setting reads in
758# a file and sets up a slew of metadata all saved in doc_obj, which
759# it then returns as part of a tuple (process_status,doc_obj)
760#
761# Much of this functionality used to reside in read, but it was broken
762# down into a supporting routine to make the code more flexible.
763#
764# recursive plugins (e.g. RecPlug) and specialized plugins like those
765# capable of processing many documents within a single file (e.g.
766# GMLPlug) will normally want to implement their own version of
767# read_into_doc_obj()
768#
769# Note that $base_dir might be "" and that $file might
770# include directories
771
772# currently blocking has been done before it gets here - does this affect secondary plugin stuff??
773sub read_into_doc_obj {
774 my $self = shift (@_);
775 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
776
777 my $outhandle = $self->{'outhandle'};
778
779 # should we move this to read? What about secondary plugins?
780 print STDERR "<Processing n='$file' p='$self->{'plugin_type'}'>\n" if ($gli);
781 print $outhandle "$self->{'plugin_type'} processing $file\n"
782 if $self->{'verbosity'} > 1;
783
784 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
785 # create a new document
786 my $doc_obj = new doc ($filename_full_path, "indexed_doc");
787 my $top_section = $doc_obj->get_top_section();
788
789 # this should look at the plugin option too...
790 $doc_obj->set_OIDtype ($processor->{'OIDtype'}, $processor->{'OIDmetadata'});
791 $doc_obj->add_utf8_metadata($top_section, "Plugin", "$self->{'plugin_type'}");
792 $doc_obj->add_utf8_metadata($top_section, "FileSize", (-s $filename_full_path));
793
794 $self->set_Source_metadata($doc_obj, $filename_no_path);
795
796 # plugin specific stuff - what args do we need here??
797 unless (defined ($self->process($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
798 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
799 return -1;
800 }
801
802 # include any metadata passed in from previous plugins
803 # note that this metadata is associated with the top level section
804 my $section = $doc_obj->get_top_section();
805 # can we merge these two methods??
806 $self->add_associated_files($doc_obj, $filename_full_path);
807 $self->extra_metadata ($doc_obj, $section, $metadata);
808 $self->auto_extract_metadata($doc_obj);
809
810 # if we haven't found any Title so far, assign one
811 # this was shifted to here from inside read()
812 $self->title_fallback($doc_obj,$section,$filename_no_path);
813
814 $self->add_OID($doc_obj);
815
816 return (1,$doc_obj);
817}
818
819sub add_dummy_text {
820 my $self = shift(@_);
821 my ($doc_obj, $section) = @_;
822
823 # add NoText metadata so we can hide this dummy text in format statements
824 $doc_obj->add_metadata($section, "NoText", "1");
825 $doc_obj->add_text($section, &gsprintf::lookup_string("{BasePlugin.dummy_text}",1));
826
827}
828
829# does nothing. Can be overridden by subclass
830sub auto_extract_metadata {
831 my $self = shift(@_);
832 my ($doc_obj) = @_;
833}
834
835# adds cover image, associate_file options stuff. Should be called by sub class
836# read_into_doc_obj
837sub add_associated_files {
838 my $self = shift(@_);
839 # whatis filename??
840 my ($doc_obj, $filename) = @_;
841
842 # add in the cover image
843 if ($self->{'cover_image'}) {
844 $self->associate_cover_image($doc_obj, $filename);
845 }
846
847
848}
849
850# implement this if you are extracting metadata for other documents
851sub metadata_read {
852 my $self = shift (@_);
853 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $extrametakeys, $extrametadata, $processor, $maxdocs, $gli) = @_;
854
855 # can we process this file??
856 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
857 return undef unless $self->can_process_this_file($filename_full_path);
858
859 return 1; # we recognise the file, but don't actually do anything with it
860}
861
862
863# The BasePlugin read() function. This function calls read_into_doc_obj()
864# to ensure all the right things to make general options work for a
865# given plugin are done. It then calls the process() function which
866# does all the work specific to a plugin (like the old read functions
867# used to do). Most plugins should define their own process() function
868# and let this read() function keep control.
869#
870# recursive plugins (e.g. RecPlug) and specialized plugins like those
871# capable of processing many documents within a single file (e.g.
872# GMLPlug) might want to implement their own version of read(), but
873# more likely need to implement their own version of read_into_doc_obj()
874#
875# Return number of files processed, undef if can't recognise, -1 if can't
876# process
877
878sub read {
879 my $self = shift (@_);
880 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
881
882 # can we process this file??
883 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
884 return undef unless $self->can_process_this_file($filename_full_path);
885
886 my ($process_status,$doc_obj) = $self->read_into_doc_obj(@_);
887
888 if ((defined $process_status) && ($process_status == 1)) {
889
890 # process the document
891 $processor->process($doc_obj);
892
893 $self->{'num_processed'} ++;
894 undef $doc_obj;
895 }
896 # delete any temp files that we may have created
897 $self->clean_up_after_doc_obj_processing();
898
899 # if process_status == 1, then the file has been processed.
900 return $process_status;
901
902}
903
904# returns undef if file is rejected by the plugin
905sub process {
906 my $self = shift (@_);
907 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
908
909 gsprintf(STDERR, "BasePlugin::process {common.must_be_implemented}\n") && die "\n";
910
911 return undef; # never gets here
912}
913
914# overwrite this method to delete any temp files that we have created
915sub clean_up_after_doc_obj_processing {
916 my $self = shift(@_);
917
918}
919
920# write_file -- used by ConvertToPlug, for example in post processing
921#
922# where should this go, is here the best place??
923sub utf8_write_file {
924 my $self = shift (@_);
925 my ($textref, $filename) = @_;
926
927 if (!open (FILE, ">$filename")) {
928 gsprintf(STDERR, "ConvertToPlug::write_file {ConvertToPlug.could_not_open_for_writing} ($!)\n", $filename);
929 die "\n";
930 }
931 print FILE $$textref;
932
933 close FILE;
934}
935
936
937sub filename_based_title
938{
939 my $self = shift (@_);
940 my ($file) = @_;
941
942 my $file_derived_title = $file;
943 $file_derived_title =~ s/_/ /g;
944 $file_derived_title =~ s/\..*?$//;
945
946 return $file_derived_title;
947}
948
949
950sub title_fallback
951{
952 my $self = shift (@_);
953 my ($doc_obj,$section,$file) = @_;
954
955 if (!defined $doc_obj->get_metadata_element ($section, "Title") or $doc_obj->get_metadata_element($section, "Title") eq "") {
956
957 my $file_derived_title = $self->filename_to_utf8_metadata($self->filename_based_title($file));
958 if (!defined $doc_obj->get_metadata_element ($section, "Title")) {
959 $doc_obj->add_utf8_metadata ($section, "Title", $file_derived_title);
960 }
961 else {
962 $doc_obj->set_utf8_metadata ($section, "Title", $file_derived_title);
963 }
964 }
965
966}
967
968# add any extra metadata that's been passed around from one
969# plugin to another.
970# extra_metadata uses add_utf8_metadata so it expects metadata values
971# to already be in utf8
972sub extra_metadata {
973 my $self = shift (@_);
974 my ($doc_obj, $cursection, $metadata) = @_;
975
976 my $associate_tail_re = $self->{'associate_tail_re'};
977
978 foreach my $field (keys(%$metadata)) {
979 # $metadata->{$field} may be an array reference
980 if ($field eq "gsdlassocfile_tobe") {
981 # 'gsdlassocfile_tobe' is artificially introduced metadata
982 # that is used to signal that certain additional files should
983 # be tied to this document. Useful in situations where a
984 # metadata pass in the plugin pipeline works out some files
985 # need to be associated with a document, but the document hasn't
986 # been formed yet.
987 my $equiv_form = "";
988 foreach my $gaf (@{$metadata->{$field}}) {
989 my ($full_filename,$mimetype) = ($gaf =~ m/^(.*):(.*):$/);
990 my ($tail_filename) = ($full_filename =~ /^.*[\/\\](.+?)$/);
991 my $filename = $full_filename;
992 $doc_obj->associate_file($full_filename,$tail_filename,$mimetype);
993
994 # work out extended tail extension (i.e. matching tail re)
995
996 my ($file_prefix,$file_extended_ext)
997 = &util::get_prefix_and_tail_by_regex($tail_filename,$associate_tail_re);
998 my ($pre_doc_ext) = ($file_extended_ext =~ m/^(.*)\..*$/);
999
1000 my ($doc_ext) = ($tail_filename =~ m/^.*\.(.*)$/);
1001 my $start_doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/{Or}{[parent(Top):archivedir],[archivedir]}/$tail_filename\">";
1002 my $srcicon = "_icon".$doc_ext."_";
1003 my $end_doclink = "</a>";
1004
1005 my $assoc_form = "$start_doclink\{If\}{$srcicon,$srcicon,$doc_ext\}$end_doclink";
1006
1007 if (defined $pre_doc_ext) {
1008 # for metadata such as [mp3._edited] [mp3._full] ...
1009 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.$pre_doc_ext", $assoc_form);
1010 }
1011
1012 # for multiple metadata such as [mp3.assoclink]
1013 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.assoclink", $assoc_form);
1014
1015 $equiv_form .= " $assoc_form";
1016 }
1017 $doc_obj->add_utf8_metadata ($cursection, "equivlink", $equiv_form);
1018 }
1019 elsif (ref ($metadata->{$field}) eq "ARRAY") {
1020 map {
1021 $doc_obj->add_utf8_metadata ($cursection, $field, $_);
1022 } @{$metadata->{$field}};
1023 } else {
1024 $doc_obj->add_utf8_metadata ($cursection, $field, $metadata->{$field});
1025 }
1026 }
1027}
1028
1029
1030sub compile_stats {
1031 my $self = shift(@_);
1032 my ($stats) = @_;
1033
1034 $stats->{'num_processed'} += $self->{'num_processed'};
1035 $stats->{'num_not_processed'} += $self->{'num_not_processed'};
1036 $stats->{'num_archives'} += $self->{'num_archives'};
1037
1038}
1039
1040sub associate_cover_image {
1041 my $self = shift;
1042 my ($doc_obj, $filename) = @_;
1043
1044 $filename =~ s/\.[^\\\/\.]+$/\.jpg/;
1045 if (exists $self->{'covers_missing_cache'}->{$filename}) {
1046 # don't stat() for existence eg for multiple document input files
1047 # (eg SplitPlug)
1048 return;
1049 }
1050
1051 my $top_section=$doc_obj->get_top_section();
1052
1053 if (-e $filename) {
1054 $doc_obj->associate_file($filename, "cover.jpg", "image/jpeg");
1055 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1056 } else {
1057 my $upper_filename = $filename;
1058 $upper_filename =~ s/jpg$/JPG/;
1059 if (-e $upper_filename) {
1060 $doc_obj->associate_file($upper_filename, "cover.jpg",
1061 "image/jpeg");
1062 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1063 } else {
1064 # file doesn't exist, so record the fact that it's missing so
1065 # we don't stat() again (stat is slow)
1066 $self->{'covers_missing_cache'}->{$filename} = 1;
1067 }
1068 }
1069
1070}
1071
1072
1073# Overridden by exploding plugins (eg. ISISPlug)
1074sub clean_up_after_exploding
1075{
1076 my $self = shift(@_);
1077}
1078
1079
1080
10811;
Note: See TracBrowser for help on using the repository browser.