root/main/trunk/greenstone2/perllib/plugins/OAIPlugin.pm @ 24971

Revision 24971, 16.8 KB (checked in by ak19, 8 years ago)

1. Introduced the util::filepath_to_url_format subroutine which will be used to convert filenames to URL style filenames to match the slashes used in the filename regex-es in extrameta keys used to index into extrameta data structures. 2. Fixed bug on windows where metadata.xml specifies filenames as regex with backslash in front of the file extension's period mark: DirectoryPlugin? needed to unregex the filepath before calling fileparse on it, else the escaping backslash would interfere with perl's fileparse routine (only on windows, since backslash also represents a dirsep here). 3. Updated all those perl plugins where the new util::filepath_to_url_format needs to be called so that they use URL style filenames (thereafter regexed) to index into the extrameta data structures.

  • Property svn:keywords set to Author Date Id Revision
Line 
1###########################################################################
2#
3# OAIPlug.pm -- basic Open Archives Initiative (OAI) plugin
4#
5# A component of the Greenstone digital library software
6# from the New Zealand Digital Library Project at the
7# University of Waikato, New Zealand.
8#
9# Copyright (C) 1999 New Zealand Digital Library Project
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation; either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program; if not, write to the Free Software
23# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24#
25###########################################################################
26
27package OAIPlugin;
28
29use extrametautil;
30use unicode;
31use util;
32
33use strict;
34no strict 'refs'; # allow filehandles to be variables and viceversa
35
36use ReadXMLFile;
37use ReadTextFile; # needed for subroutine textcat_get_language_encoding
38use metadatautil;
39use MetadataRead;
40use util;
41
42# methods with identical signatures take precedence in the order given in the ISA list.
43sub BEGIN {
44    @OAIPlugin::ISA = ('MetadataRead', 'ReadXMLFile', 'ReadTextFile');
45}
46
47my $set_list =
48    [ { 'name' => "auto",
49    'desc' => "{OAIPlugin.metadata_set.auto}" },
50      { 'name' => "dc",
51    'desc' => "{OAIPlugin.metadata_set.dc}" }
52      ];
53
54my $arguments =
55    [ { 'name' => "process_exp",
56    'desc' => "{BasePlugin.process_exp}",
57    'type' => "regexp",
58    'reqd' => "no",
59    'deft' => &get_default_process_exp() },
60      { 'name' => "metadata_set",
61    'desc' => "{OAIPlugin.metadata_set}",
62    'type' => "enumstring",
63    'reqd' => "no",
64    'list' => $set_list,
65    'deft' => "dc" },
66      { 'name' => "document_field",
67    'desc' => "{OAIPlugin.document_field}",
68    'type' => "metadata",
69    'reqd' => "no",
70    'deft' => "gi.Sourcedoc" }
71      ];
72
73my $options = { 'name'     => "OAIPlugin",
74        'desc'     => "{OAIPlugin.desc}",
75        'abstract' => "no",
76        'inherits' => "yes",
77        'explodes' => "yes",
78        'args'     => $arguments };
79
80
81sub new {
82    my ($class) = shift (@_);
83    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
84    push(@$pluginlist, $class);
85
86    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
87    push(@{$hashArgOptLists->{"OptList"}},$options);
88
89    new ReadTextFile($pluginlist, $inputargs, $hashArgOptLists,1);
90    my $self = new ReadXMLFile($pluginlist, $inputargs, $hashArgOptLists);
91
92    if ($self->{'info_only'}) {
93    # don't worry about modifying options
94    return bless $self, $class;
95    }
96    # trim any ex. from document field iff it's the only metadata namespace prefix   
97    $self->{'document_field'} =~ s/^ex\.([^.]+)$/$1/;
98    return bless $self, $class;
99}
100
101sub get_default_process_exp {
102    my $self = shift (@_);
103
104    return q^(?i)(\.oai)$^;
105}
106
107sub get_doctype {
108    my $self = shift(@_);
109   
110    return "OAI-PMH";
111}
112
113sub xml_start_document {
114    my $self = shift (@_);
115    $self->{'in_metadata_node'} = 0;
116    $self->{'rawxml'} = "";
117    $self->{'saved_metadata'} = {};
118}
119
120sub xml_end_document {
121}
122
123sub xml_doctype {
124    my $self = shift(@_);
125
126    my ($expat, $name, $sysid, $pubid, $internal) = @_;
127
128    ##die "" if ($name !~ /^OAI-PMH$/);
129
130    my $outhandle = $self->{'outhandle'};
131    print $outhandle "OAIPlugin: processing $self->{'file'}\n" if $self->{'verbosity'} > 1;
132    print STDERR "<Processing n='$self->{'file'}' p='OAIPlugin'>\n" if $self->{'gli'};
133
134}
135
136
137sub xml_start_tag {
138    my $self = shift(@_);
139    my ($expat,$element) = @_;
140
141    my %attr_hash = %_;
142
143    my $attr = "";
144    map { $attr .= " $_=$attr_hash{$_}"; } keys %attr_hash;
145
146    $self->{'rawxml'} .= "<$element$attr>";
147
148    if ($element eq "metadata") {
149    $self->{'in_metadata_node'} = 1;
150    $self->{'metadata_xml'} = "";
151    }
152
153    if ($self->{'in_metadata_node'}) {
154    $self->{'metadata_xml'} .= "<$element$attr>";
155    }
156}
157
158sub xml_end_tag {
159    my $self = shift(@_);
160    my ($expat, $element) = @_;
161
162    $self->{'rawxml'} .= "</$element>";
163
164    if ($self->{'in_metadata_node'}) {
165    $self->{'metadata_xml'} .= "</$element>";
166    }
167
168    if ($element eq "metadata") {
169    my $textref = \$self->{'metadata_xml'};
170    #my $metadata = $self->{'metadata'};
171    my $metadata = $self->{'saved_metadata'};
172    $self->extract_oai_metadata($textref,$metadata);
173
174    $self->{'in_metadata_node'} = 0;   
175    }
176
177
178}
179
180sub xml_text {
181    my $self = shift(@_);
182    my ($expat) = @_;
183
184    $self->{'rawxml'} .= $_;
185
186    if ($self->{'in_metadata_node'}) {
187    $self->{'metadata_xml'} .= $_;
188    }
189}
190
191
192sub metadata_read {
193    my $self = shift (@_); 
194
195    my ($pluginfo, $base_dir, $file, $block_hash,
196    $extrametakeys, $extrametadata, $extrametafile,
197    $processor, $gli, $aux) = @_;
198
199    # can we process this file??
200    my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
201    return undef unless $self->can_process_this_file_for_metadata($filename_full_path);
202   
203    if (!$self->parse_file($filename_full_path, $file, $gli)) {
204    $self->{'saved_metadata'} = undef;
205    return undef;
206    }
207
208    my $new_metadata = $self->{'saved_metadata'};
209    $self->{'saved_metadata'} = undef;
210
211    # add the pretty metadata table as metadata
212    my $ppmd_table = $self->{'ppmd_table'};
213    $new_metadata->{'prettymd'} = $ppmd_table;
214    $self->{'ppmd_table'} = undef;
215     
216    my $document_metadata_field = $self->{'document_field'};
217    my $url_array = $new_metadata->{$document_metadata_field};
218    if (!defined $url_array) {
219    # try ex.
220    $url_array = $new_metadata->{"ex.$document_metadata_field"};
221    }
222    my $num_urls = (defined $url_array) ? scalar(@$url_array) : 0;
223    ##print STDERR "$num_urls urls for $file\n";
224    my $srcdoc_exists = 0;
225    my $srcdoc_pos = 0;
226    my $filename_dir = &util::filename_head($filename_full_path);
227   
228    # filenames in extrametadata must be relative to current dir, as
229    # DirectoryPlugin adds path info on itself
230    my ($filename_for_metadata) = $file =~ /([^\\\/]+)$/; # this assumes there will only be one record per oai file - is this always the case??
231    for (my $i=0; $i<$num_urls; $i++) {
232   
233    if ($url_array->[$i] !~ m/^(https?|ftp):/) {
234       
235        my $src_filename = &util::filename_cat($filename_dir, $url_array->[$i]);
236        if (-e $src_filename) {
237        $srcdoc_pos = $i;
238        $srcdoc_exists = 1;
239        # get the slashes the right way, use filename_cat
240        $filename_for_metadata = &util::filename_cat($url_array->[$i]);
241        last;
242        }
243    }
244    }
245   
246    if ($srcdoc_exists) {
247    $self->{'oai-files'}->{$file}->{'srcdoc_exists'} = 1;
248    }
249    else {
250    # save the rawxml for the source document
251    $self->{'oai-files'}->{$file}->{'srcdoc_exists'} = 0;
252    $self->{'oai-files'}->{$file}->{'rawxml'} = $self->{'rawxml'};
253    $self->{'rawxml'} = "";
254    }
255   
256    # return all the metadata we have extracted to the caller.
257    # Directory plug will pass it back in at read time, so we don't need to extract it again.
258   
259    # Extrametadata keys should be regular expressions
260    # Indexing into the extrameta data structures requires the filename's style of slashes to be in URL format
261    # Then need to convert the filename to a regex, no longer to protect windows directory chars \, but for
262    # protecting special characters like brackets in the filepath such as "C:\Program Files (x86)\Greenstone".
263    $filename_for_metadata = &util::filepath_to_url_format($filename_for_metadata);
264    $filename_for_metadata = &util::filename_to_regex($filename_for_metadata);
265   
266    &extrametautil::setmetadata($extrametadata, $filename_for_metadata, $new_metadata);
267    &extrametautil::addmetakey($extrametakeys, $filename_for_metadata);
268    if ($srcdoc_exists) {   
269    if (!defined &extrametautil::getmetafile($extrametafile, $filename_for_metadata)) {
270        &extrametautil::setmetafile($extrametafile, $filename_for_metadata, {});
271    }
272     #maps the file to full path
273    &extrametautil::setmetafile_for_named_file($extrametafile, $filename_for_metadata, $file, $filename_full_path);
274   
275    }
276    return 1;
277   
278}
279
280
281sub read {
282    my $self = shift (@_); 
283   
284    my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
285
286    if (!defined $self->{'oai-files'}->{$file}) {
287    return undef;
288    }
289       
290    my $srcdoc_exists = $self->{'oai-files'}->{$file}->{'srcdoc_exists'};
291    if ($srcdoc_exists) {
292    # do nothing more - all the metadata has been extracted and associated with the srcdoc
293    # no more need to access details of this $file => tidy up as you go
294    delete $self->{'oai-files'}->{$file};
295    return 0; # not processed here, but don't pass on to rest of plugins
296    }
297
298    my $filename = $file;
299    $filename = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
300
301    # Do encoding stuff on metadata
302    my ($language, $encoding) = $self->textcat_get_language_encoding ($filename);
303
304    # create a new document
305    my $doc_obj = new doc ($filename, "indexed_doc", $self->{'file_rename_method'});
306    my $top_section = $doc_obj->get_top_section;
307    my $plugin_type = $self->{'plugin_type'};
308   
309    my ($filemeta) = $file =~ /([^\\\/]+)$/;
310    my $plugin_filename_encoding = $self->{'filename_encoding'};
311    my $filename_encoding = $self->deduce_filename_encoding($file,$metadata,$plugin_filename_encoding);
312    $self->set_Source_metadata($doc_obj, $filename, $filename_encoding);
313
314    $doc_obj->add_utf8_metadata($top_section, "Language", $language);
315    $doc_obj->add_utf8_metadata($top_section, "Encoding", $encoding);
316    $doc_obj->add_utf8_metadata($top_section, "Plugin", $plugin_type);
317    $doc_obj->add_metadata($top_section, "FileFormat", "OAI");
318    $doc_obj->add_metadata($top_section, "FileSize", (-s $filename));
319   
320    # include any metadata passed in from previous plugins
321    # note that this metadata is associated with the top level section
322    # this will include all the metadata from the oai file that we extracted
323    # during metadata_read
324    $self->extra_metadata ($doc_obj, $doc_obj->get_top_section(), $metadata);
325   
326    # do plugin specific processing of doc_obj
327    my $text = $self->{'oai-files'}->{$file}->{'rawxml'};
328    delete $self->{'oai-files'}->{$file};
329
330    unless (defined ($self->process(\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj))) {
331    print STDERR "<ProcessingError n='$file'>\n" if ($gli);
332    return -1;
333    }
334   
335    # do any automatic metadata extraction
336    $self->auto_extract_metadata ($doc_obj);
337   
338    # add an OID
339    $self->add_OID($doc_obj);
340       
341    # process the document
342    $processor->process($doc_obj);
343   
344    $self->{'num_processed'} ++;
345   
346    return 1; # processed the file
347}
348
349
350# do plugin specific processing of doc_obj
351sub process {
352    my $self = shift (@_);
353    my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
354    my $outhandle = $self->{'outhandle'};
355
356    print STDERR "<Processing n='$file' p='OAIPlugin'>\n" if ($gli);
357    print $outhandle "OAIPlugin: processing $file\n"
358    if $self->{'verbosity'} > 1;
359
360    my $cursection = $doc_obj->get_top_section();
361
362##    $self->extract_metadata ($textref, $metadata, $doc_obj, $cursection);
363
364    # add text to document object
365
366#    $$textref =~ s/<(.*?)>/$1 /g;
367    $$textref =~ s/</&lt;/g;
368    $$textref =~ s/>/&gt;/g;
369    $$textref =~ s/\[/&#91;/g;
370    $$textref =~ s/\]/&#93;/g;
371
372    $doc_obj->add_utf8_text($cursection, $$textref);
373
374    return 1;
375}
376
377
378# Improvement is to merge this with newer version in MetadataPass
379
380sub open_prettyprint_metadata_table
381{
382    my $self = shift(@_);
383
384    my $att   = "width=100% cellspacing=2";
385    my $style = "style=\'border-bottom: 4px solid #000080\'";
386
387    $self->{'ppmd_table'} = "\n<table $att $style>";
388}
389
390sub add_prettyprint_metadata_line
391{
392    my $self = shift(@_);
393    my ($metaname, $metavalue_utf8) = @_;
394
395    $metavalue_utf8 = &util::hyperlink_text($metavalue_utf8);
396
397    $self->{'ppmd_table'} .= "  <tr bgcolor=#b5d3cd>\n";
398    $self->{'ppmd_table'} .= "    <td width=30%>\n";
399    $self->{'ppmd_table'} .= "      $metaname\n";
400    $self->{'ppmd_table'} .= "    </td>\n";
401    $self->{'ppmd_table'} .= "    <td>\n";
402    $self->{'ppmd_table'} .= "      $metavalue_utf8\n";
403    $self->{'ppmd_table'} .= "    </td>\n";
404    $self->{'ppmd_table'} .= "  </tr>\n";
405
406}
407
408sub close_prettyprint_metadata_table
409{
410    my $self = shift(@_);
411
412    $self->{'ppmd_table'} .= "</table>\n";
413}
414
415my $qualified_dc_mapping = {
416    "alternative" => "dc.title",
417    "tableOfContents" => "dc.description",
418    "abstract" => "dc.description",
419    "created" => "dc.date",
420    "valid" => "dc.date",
421    "available" => "dc.date",
422    "issued" => "dc.date",
423    "modified" => "dc.date",
424    "dateAccepted" => "dc.date",
425    "dateCopyrighted" => "dc.date",
426    "dateSubmitted" => "dc.date",
427    "extent" => "dc.format",
428    "medium" => "dc.format",
429    "isVersionOf" => "dc.relation",
430    "hasVersion" => "dc.relation",
431    "isReplacedBy" => "dc.relation",
432    "replaces" => "dc.relation",
433    "isRequiredBy" => "dc.relation",
434    "requires" => "dc.relation",
435    "isPartOf" => "dc.relation",
436    "hasPart" => "dc.relation",
437    "isReferencedBy" => "dc.relation",
438    "references" => "dc.relation",
439    "isFormatOf" => "dc.relation",
440    "hasFormat" => "dc.relation",
441    "conformsTo" => "dc.relation",
442    "spatial" => "dc.coverage",
443    "temporal" => "dc.coverage",
444# these are now top level elements in our qualified dc metadata set
445#   "audience" => "dc.any",
446#   "accrualMethod" => "dc.any",
447#   "accrualPeriodicity" => "dc.any",
448#   "accrualPolicy" => "dc.any",
449#   "instructionalMethod" => "dc.any",
450#   "provenance" => "dc.any",
451#   "rightsHolder" => "dc.any",
452    "mediator" => "dc.audience",
453    "educationLevel" => "dc.audience",
454    "accessRights" => "dc.rights",
455    "license" => "dc.rights",
456    "bibliographicCitation" => "dc.identifier"
457    };
458
459sub remap_dc_metadata
460{
461    my $self = shift(@_);
462
463    my ($metaname) = @_;
464
465    my ($prefix,$name) = ($metaname =~ m/^(.*?)\.(.*?)$/);
466   
467    if (defined $qualified_dc_mapping->{$name}) {
468   
469    return $qualified_dc_mapping->{$name}."^".$name;
470    }
471   
472   
473    return $metaname; # didn't get a match, return param passed in unchanged
474}
475
476
477sub extract_oai_metadata {
478    my $self = shift (@_);
479    my ($textref, $metadata) = @_;
480    my $outhandle = $self->{'outhandle'};
481
482    $self->open_prettyprint_metadata_table();
483
484    if ($$textref =~ m/<metadata\s*>(.*?)<\/metadata\s*>/s)
485    {
486    my $metadata_text = $1;
487
488    # locate and remove outermost tag (ignoring any attribute information in top-level tag)
489    my ($outer_tagname,$inner_metadata_text) = ($metadata_text =~ m/<([^ >]+).*?>(.*?)<\/\1>/s);
490    # split tag into namespace and tag name
491    my($namespace,$top_level_prefix) = ($outer_tagname =~ m/^(.*?):(.*?)$/);
492    # sometimes, the dc namespace is not specified as the prefix in each element (like <dc:title>)
493    # but is rather defined in the wrapper element containing the various dc meta elements,
494    # like <dc><title></title><creator></creator></dc>.
495    # In such a case, we use this wrapper element as the top_level_prefix
496   
497    # if there was no prefix, then the tag itself becomes the top_level_prefix
498    if(!defined $top_level_prefix && defined $outer_tagname) {
499        $top_level_prefix = $outer_tagname;
500    }
501
502    #process each element one by one
503    while ($inner_metadata_text =~ m/<([^ >]+).*?>(.*?)<\/\1>(.*)/s)
504    {
505
506        my $metaname = $1;
507        my $metavalue = $2;
508        $inner_metadata_text = $3;
509
510        # greenstone uses . for namespace, while oai uses :
511        $metaname =~ s/:/\./;
512        # if there is no namespace, then we use the outer tag name or
513        # namespace for this element
514        if ($metaname !~ m/\./)
515        {
516        $metaname = "$top_level_prefix.$metaname";
517        }
518       
519        # if metadata set is auto, leave as is, otherwise convert to
520        # specified namespace
521        if ($self->{'metadata_set'} ne "auto") {
522        if ($metaname !~ /^gi\./) { # hack to not overwrite gi metadata
523            $metaname =~ s/^([^\.]*)\./$self->{'metadata_set'}\./;
524            if ($self->{'metadata_set'} eq "dc") {
525            # convert qualified dc terms to gs version, e.g.
526            # spatial becomes coverage^spatial
527            $metaname = $self->remap_dc_metadata($metaname);
528            }
529        }
530        }
531
532        # uppercase the first char of the name
533        $metaname =~ s/\.(.)/\.\u$1/;
534        $metavalue =~ s/\[/&#91;/g;
535        $metavalue =~ s/\]/&#93;/g;
536
537        # so that GLI can see this metadata, store here as ex.dc.Title etc
538        my $ex_metaname = $metaname;
539        $ex_metaname =~ s/^ex\.//; # remove any pre-existing ex. prefix
540        $ex_metaname = "ex.$ex_metaname"; # at last can prefix ex.
541
542        if (defined $metadata->{$ex_metaname})
543        {
544        push(@{$metadata->{$ex_metaname}},$metavalue);
545
546        }
547        else
548        {
549        $metadata->{$ex_metaname} = [ $metavalue ];
550        }
551
552        # but don't add ex to the pretty print line
553        $self->add_prettyprint_metadata_line($metaname, $metavalue);
554       
555    }
556    }
557
558    $self->close_prettyprint_metadata_table();
559}
560
561## we know from the file extension, so doesn't need to check the doctype
562sub check_doctype {
563
564    return 1;
565}
566
5671;
Note: See TracBrowser for help on using the browser.