root/gsdl/trunk/perllib/plugins/BasePlugin.pm @ 16643

Revision 16643, 32.3 KB (checked in by kjdon, 12 years ago)

removed a couple of 'use xxx' lines that are not needed

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