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

Last change on this file since 16919 was 16919, checked in by ak19, 16 years ago

set_Source_metadata modified to also set SourceFile metadata which represents the URL-encoded version of the original sourcefile. In case the original sourcefile is already url-encoded, SourceFile metadata will escape percent signs with percent 25.

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