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

Revision 16767, 31.8 KB (checked in by ak19, 12 years ago)

In progress: Filename encoding after working with it on Windows. Still need to get interlinking html files (with multilingual filenames) working

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