root/main/trunk/greenstone2/perllib/plugins/BasePlugin.pm @ 21308

Revision 21308, 36.3 KB (checked in by kjdon, 10 years ago)

removeold renamed to remove_all, added remove_one for deleting a single doc

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