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

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

removed the metadata argument from metadata_read as its not used and just confuses things when implementing this

  • Property svn:keywords set to Author Date Id Revision
File size: 33.6 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 textstring using textcat
628 $self->{'textcat'} = new textcat() unless defined($self->{'textcat'});
629 my $results = $self->{'textcat'}->classify_cached_filename(\$text);
630
631
632 if (scalar @$results < 0) {
633 return undef;
634 }
635
636 # We have some results, we choose the first
637 my ($language, $encoding) = $results->[0] =~ /^([^-]*)(?:-(.*))?$/;
638
639 $best_encoding = $encoding;
640 if (!defined $best_encoding) {
641 return undef;
642 }
643
644 if (defined $best_encoding && $best_encoding =~ m/^iso_8859/ && &unicode::check_is_utf8($text)) {
645 # the text is valid utf8, so assume that's the real encoding (since textcat is based on probabilities)
646 $best_encoding = 'utf8';
647 }
648
649
650 # check for equivalents where textcat doesn't have some encodings...
651 # eg MS versions of standard encodings
652 if (defined $best_encoding && $best_encoding =~ /^iso_8859_(\d+)/) {
653 my $iso = $1; # which variant of the iso standard?
654 # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
655 if ($text =~ /[\x80-\x9f]/) {
656 # Western Europe
657 if ($iso == 1 or $iso == 15) { $best_encoding = 'windows_1252' }
658 elsif ($iso == 2) {$best_encoding = 'windows_1250'} # Central Europe
659 elsif ($iso == 5) {$best_encoding = 'windows_1251'} # Cyrillic
660 elsif ($iso == 6) {$best_encoding = 'windows_1256'} # Arabic
661 elsif ($iso == 7) {$best_encoding = 'windows_1253'} # Greek
662 elsif ($iso == 8) {$best_encoding = 'windows_1255'} # Hebrew
663 elsif ($iso == 9) {$best_encoding = 'windows_1254'} # Turkish
664 }
665 }
666
667 if (defined $best_encoding && $best_encoding !~ /^(ascii|utf8|unicode)$/ &&
668 !defined $encodings::encodings->{$best_encoding})
669 {
670 if ($self->{'verbosity'}) {
671 gsprintf($outhandle, "BasePlugin: {ReadTextFile.unsupported_encoding}\n", $text, $best_encoding, "undef");
672 }
673 $best_encoding = undef;
674 }
675
676 return $best_encoding;
677}
678
679# uses locale
680sub get_filesystem_encoding {
681
682 my $self = shift(@_);
683
684 my $outhandle = $self->{'outhandle'};
685 my $filesystem_encoding = undef;
686
687 eval {
688 use POSIX qw(locale_h);
689
690 # With only one parameter, setlocale retrieves the
691 # current value
692 my $current_locale = setlocale(LC_CTYPE);
693
694 if ($current_locale =~ m/^.*\.(.*?)$/) {
695 my $char_encoding = lc($1);
696 if ($char_encoding =~ m/^(iso)(8859)(\d{1,2})$/) {
697 $char_encoding = "$1\_$2\_$3";
698 }
699
700 $char_encoding =~ s/-/_/g;
701 $char_encoding =~ s/^utf_8$/utf8/;
702
703 if ($char_encoding =~ m/^\d+$/) {
704 if (defined $encodings::encodings->{"windows_$char_encoding"}) {
705 $char_encoding = "windows_$char_encoding";
706 }
707 elsif (defined $encodings::encodings->{"dos_$char_encoding"}) {
708 $char_encoding = "dos_$char_encoding";
709 }
710 }
711
712 if (($char_encoding =~ m/(?:ascii|utf8|unicode)/)
713 || (defined $encodings::encodings->{$char_encoding})) {
714 $filesystem_encoding = $char_encoding;
715 }
716 else {
717 print $outhandle "Warning: Unsupported character encoding '$char_encoding' from locale '$current_locale'\n";
718 }
719 }
720
721
722 };
723 if ($@) {
724 print $outhandle "$@\n";
725 print $outhandle "Warning: Unable to establish locale. Will assume filesytem is UTF-8\n";
726
727 }
728 return $filesystem_encoding;
729}
730
731# is there ever only one Source? Sometimes this will be called twice, for images etc that are converted.
732sub set_Source_metadata {
733 my $self = shift (@_);
734 my ($doc_obj, $filename_no_path, $file_encoding) = @_;
735
736
737 my $top_section = $doc_obj->get_top_section();
738
739 # UTF-8 version of filename
740 my $filemeta = $self->filename_to_utf8_metadata($filename_no_path, $file_encoding);
741
742 # Source is the UTF8 display name - not necessarily the name of the file on the system
743 $doc_obj->set_utf8_metadata_element($top_section, "Source", $filemeta);
744
745 # SourceFile is the url-reference to url-encoded filemeta:
746 # it's a url that refers to the actual file on the system
747 $filemeta = &unicode::url_encode($filemeta);
748 $filemeta = &unicode::filename_to_url($filemeta);
749 $doc_obj->set_utf8_metadata_element($top_section, "SourceFile", $filemeta);
750}
751
752# this should be called by all plugins to set the oid of the doc obj, rather
753# than calling doc_obj->set_OID directly
754sub add_OID {
755 my $self = shift (@_);
756 my ($doc_obj) = @_;
757
758 $doc_obj->set_OIDtype($self->{'OIDtype'}, $self->{'OIDmetadata'});
759
760 # see if there is a plugin specific set_OID function
761 if (defined ($self->can('set_OID'))) {
762 $self->set_OID(@_); # pass through doc_obj and any extra arguments
763 }
764 else {
765 # use the default set_OID() in doc.pm
766 $doc_obj->set_OID();
767 }
768
769}
770
771# The BasePlugin read_into_doc_obj() function. This function does all the
772# right things to make general options work for a given plugin. It doesn't do anything with the file other than setting reads in
773# a file and sets up a slew of metadata all saved in doc_obj, which
774# it then returns as part of a tuple (process_status,doc_obj)
775#
776# Much of this functionality used to reside in read, but it was broken
777# down into a supporting routine to make the code more flexible.
778#
779# recursive plugins (e.g. RecPlug) and specialized plugins like those
780# capable of processing many documents within a single file (e.g.
781# GMLPlug) will normally want to implement their own version of
782# read_into_doc_obj()
783#
784# Note that $base_dir might be "" and that $file might
785# include directories
786
787# currently blocking has been done before it gets here - does this affect secondary plugin stuff??
788sub read_into_doc_obj {
789 my $self = shift (@_);
790 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
791
792 my $outhandle = $self->{'outhandle'};
793
794 # should we move this to read? What about secondary plugins?
795 print STDERR "<Processing n='$file' p='$self->{'plugin_type'}'>\n" if ($gli);
796 print $outhandle "$self->{'plugin_type'} processing $file\n"
797 if $self->{'verbosity'} > 1;
798
799 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
800 # create a new document
801 my $doc_obj = new doc ($filename_full_path, "indexed_doc");
802 my $top_section = $doc_obj->get_top_section();
803
804 $doc_obj->add_utf8_metadata($top_section, "Plugin", "$self->{'plugin_type'}");
805 $doc_obj->add_utf8_metadata($top_section, "FileSize", (-s $filename_full_path));
806
807 # sets the UTF8 filename (Source) for display and sets the url ref to URL encoded version
808 # of the UTF8 filename (SourceFile) for generated files
809 $self->set_Source_metadata($doc_obj, $filename_no_path);
810
811 # plugin specific stuff - what args do we need here??
812 unless (defined ($self->process($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
813 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
814 return -1;
815 }
816
817 # include any metadata passed in from previous plugins
818 # note that this metadata is associated with the top level section
819 my $section = $doc_obj->get_top_section();
820 # can we merge these two methods??
821 $self->add_associated_files($doc_obj, $filename_full_path);
822 $self->extra_metadata ($doc_obj, $section, $metadata);
823 $self->auto_extract_metadata($doc_obj);
824
825 # if we haven't found any Title so far, assign one
826 # this was shifted to here from inside read()
827 $self->title_fallback($doc_obj,$section,$filename_no_path);
828
829 $self->add_OID($doc_obj);
830
831 return (1,$doc_obj);
832}
833
834sub add_dummy_text {
835 my $self = shift(@_);
836 my ($doc_obj, $section) = @_;
837
838 # add NoText metadata so we can hide this dummy text in format statements
839 $doc_obj->add_metadata($section, "NoText", "1");
840 $doc_obj->add_text($section, &gsprintf::lookup_string("{BasePlugin.dummy_text}",1));
841
842}
843
844# does nothing. Can be overridden by subclass
845sub auto_extract_metadata {
846 my $self = shift(@_);
847 my ($doc_obj) = @_;
848}
849
850# adds cover image, associate_file options stuff. Should be called by sub class
851# read_into_doc_obj
852sub add_associated_files {
853 my $self = shift(@_);
854 # whatis filename??
855 my ($doc_obj, $filename) = @_;
856
857 # add in the cover image
858 if ($self->{'cover_image'}) {
859 $self->associate_cover_image($doc_obj, $filename);
860 }
861
862
863}
864
865# implement this if you are extracting metadata for other documents
866sub metadata_read {
867 my $self = shift (@_);
868 my ($pluginfo, $base_dir, $file, $block_hash, $extrametakeys, $extrametadata, $processor, $maxdocs, $gli) = @_;
869
870 # can we process this file??
871 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
872 return undef unless $self->can_process_this_file($filename_full_path);
873
874 return 1; # we recognise the file, but don't actually do anything with it
875}
876
877
878# The BasePlugin read() function. This function calls read_into_doc_obj()
879# to ensure all the right things to make general options work for a
880# given plugin are done. It then calls the process() function which
881# does all the work specific to a plugin (like the old read functions
882# used to do). Most plugins should define their own process() function
883# and let this read() function keep control.
884#
885# recursive plugins (e.g. RecPlug) and specialized plugins like those
886# capable of processing many documents within a single file (e.g.
887# GMLPlug) might want to implement their own version of read(), but
888# more likely need to implement their own version of read_into_doc_obj()
889#
890# Return number of files processed, undef if can't recognise, -1 if can't
891# process
892
893sub read {
894 my $self = shift (@_);
895 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
896
897 # can we process this file??
898 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
899 return undef unless $self->can_process_this_file($filename_full_path);
900
901 my ($process_status,$doc_obj) = $self->read_into_doc_obj(@_);
902
903 if ((defined $process_status) && ($process_status == 1)) {
904
905 # process the document
906 $processor->process($doc_obj);
907
908 $self->{'num_processed'} ++;
909 undef $doc_obj;
910 }
911 # delete any temp files that we may have created
912 $self->clean_up_after_doc_obj_processing();
913
914 # if process_status == 1, then the file has been processed.
915 return $process_status;
916
917}
918
919# returns undef if file is rejected by the plugin
920sub process {
921 my $self = shift (@_);
922 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
923
924 gsprintf(STDERR, "BasePlugin::process {common.must_be_implemented}\n") && die "\n";
925
926 return undef; # never gets here
927}
928
929# overwrite this method to delete any temp files that we have created
930sub clean_up_after_doc_obj_processing {
931 my $self = shift(@_);
932
933}
934
935# write_file -- used by ConvertToPlug, for example in post processing
936#
937# where should this go, is here the best place??
938sub utf8_write_file {
939 my $self = shift (@_);
940 my ($textref, $filename) = @_;
941
942 if (!open (FILE, ">$filename")) {
943 gsprintf(STDERR, "ConvertToPlug::write_file {ConvertToPlug.could_not_open_for_writing} ($!)\n", $filename);
944 die "\n";
945 }
946 print FILE $$textref;
947
948 close FILE;
949}
950
951
952sub filename_based_title
953{
954 my $self = shift (@_);
955 my ($file) = @_;
956
957 my $file_derived_title = $file;
958 $file_derived_title =~ s/_/ /g;
959 $file_derived_title =~ s/\..*?$//;
960
961 return $file_derived_title;
962}
963
964
965sub title_fallback
966{
967 my $self = shift (@_);
968 my ($doc_obj,$section,$file) = @_;
969
970 if (!defined $doc_obj->get_metadata_element ($section, "Title") or $doc_obj->get_metadata_element($section, "Title") eq "") {
971
972 my $file_derived_title = $self->filename_to_utf8_metadata($self->filename_based_title($file));
973 if (!defined $doc_obj->get_metadata_element ($section, "Title")) {
974 $doc_obj->add_utf8_metadata ($section, "Title", $file_derived_title);
975 }
976 else {
977 $doc_obj->set_utf8_metadata_element ($section, "Title", $file_derived_title);
978 }
979 }
980
981}
982
983# add any extra metadata that's been passed around from one
984# plugin to another.
985# extra_metadata uses add_utf8_metadata so it expects metadata values
986# to already be in utf8
987sub extra_metadata {
988 my $self = shift (@_);
989 my ($doc_obj, $cursection, $metadata) = @_;
990
991 my $associate_tail_re = $self->{'associate_tail_re'};
992
993 foreach my $field (keys(%$metadata)) {
994 # $metadata->{$field} may be an array reference
995 if ($field eq "gsdlassocfile_tobe") {
996 # 'gsdlassocfile_tobe' is artificially introduced metadata
997 # that is used to signal that certain additional files should
998 # be tied to this document. Useful in situations where a
999 # metadata pass in the plugin pipeline works out some files
1000 # need to be associated with a document, but the document hasn't
1001 # been formed yet.
1002 my $equiv_form = "";
1003 foreach my $gaf (@{$metadata->{$field}}) {
1004 my ($full_filename,$mimetype) = ($gaf =~ m/^(.*):(.*):$/);
1005 #my ($tail_filename) = ($full_filename =~ /^.*[\/\\](.+?)$/);
1006 my $tail_filename = $doc_obj->get_assocfile_from_sourcefile();
1007 my $filename = $full_filename;
1008 $doc_obj->associate_file($full_filename,$tail_filename,$mimetype);
1009
1010 # work out extended tail extension (i.e. matching tail re)
1011
1012 my ($file_prefix,$file_extended_ext)
1013 = &util::get_prefix_and_tail_by_regex($tail_filename,$associate_tail_re);
1014 my ($pre_doc_ext) = ($file_extended_ext =~ m/^(.*)\..*$/);
1015
1016 my ($doc_ext) = ($tail_filename =~ m/^.*\.(.*)$/);
1017 my $start_doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/{Or}{[parent(Top):archivedir],[archivedir]}/$tail_filename\">";
1018 my $srcicon = "_icon".$doc_ext."_";
1019 my $end_doclink = "</a>";
1020
1021 my $assoc_form = "$start_doclink\{If\}{$srcicon,$srcicon,$doc_ext\}$end_doclink";
1022
1023 if (defined $pre_doc_ext) {
1024 # for metadata such as [mp3._edited] [mp3._full] ...
1025 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.$pre_doc_ext", $assoc_form);
1026 }
1027
1028 # for multiple metadata such as [mp3.assoclink]
1029 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.assoclink", $assoc_form);
1030
1031 $equiv_form .= " $assoc_form";
1032 }
1033 $doc_obj->add_utf8_metadata ($cursection, "equivlink", $equiv_form);
1034 }
1035 elsif (ref ($metadata->{$field}) eq "ARRAY") {
1036 map {
1037 $doc_obj->add_utf8_metadata ($cursection, $field, $_);
1038 } @{$metadata->{$field}};
1039 } else {
1040 $doc_obj->add_utf8_metadata ($cursection, $field, $metadata->{$field});
1041 }
1042 }
1043}
1044
1045
1046sub compile_stats {
1047 my $self = shift(@_);
1048 my ($stats) = @_;
1049
1050 $stats->{'num_processed'} += $self->{'num_processed'};
1051 $stats->{'num_not_processed'} += $self->{'num_not_processed'};
1052 $stats->{'num_archives'} += $self->{'num_archives'};
1053
1054}
1055
1056sub associate_cover_image {
1057 my $self = shift;
1058 my ($doc_obj, $filename) = @_;
1059
1060 $filename =~ s/\.[^\\\/\.]+$/\.jpg/;
1061 if (exists $self->{'covers_missing_cache'}->{$filename}) {
1062 # don't stat() for existence eg for multiple document input files
1063 # (eg SplitPlug)
1064 return;
1065 }
1066
1067 my $top_section=$doc_obj->get_top_section();
1068
1069 if (-e $filename) {
1070 $doc_obj->associate_file($filename, "cover.jpg", "image/jpeg");
1071 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1072 } else {
1073 my $upper_filename = $filename;
1074 $upper_filename =~ s/jpg$/JPG/;
1075 if (-e $upper_filename) {
1076 $doc_obj->associate_file($upper_filename, "cover.jpg",
1077 "image/jpeg");
1078 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1079 } else {
1080 # file doesn't exist, so record the fact that it's missing so
1081 # we don't stat() again (stat is slow)
1082 $self->{'covers_missing_cache'}->{$filename} = 1;
1083 }
1084 }
1085
1086}
1087
1088
1089# Overridden by exploding plugins (eg. ISISPlug)
1090sub clean_up_after_exploding
1091{
1092 my $self = shift(@_);
1093}
1094
1095
1096
10971;
Note: See TracBrowser for help on using the repository browser.