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

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

OID generation modifications: OIDtype and OIDmetadata options now available for plugins as well as import. OIDtype for plugins defaults to auto - if set to auto, then use the values from import. All plugins now call self->add_OID instead of doc_obj->set_OID. This sets the doc_obj OIDtype so that doesn't need to be donein other places any more. all plugins have the get_oid_hash_type method - normally returns hash_on_file, but can be overridden to return hash_on_ga_xml for those plugins that don't want hashing on file (MP3,OggVorbis...)

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