source: trunk/gsdl/perllib/plugins/RecPlug.pm@ 9462

Last change on this file since 9462 was 9462, checked in by mdewsnip, 19 years ago

Added "use bytes" in all XML::Parser Char functions. This is to prevent nasty encoding problems when using XML::Parser versions 2.31+. See BasPlug's revision 1.58 log message for more information on this problem.

With much help from John McPherson.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 20.5 KB
Line 
1###########################################################################
2#
3# RecPlug.pm --
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 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
26# RecPlug is a plugin which recurses through directories processing
27# each file it finds.
28
29# RecPlug has one option: use_metadata_files. When this is set, it will
30# check each directory for an XML file called "metadata.xml" that specifies
31# metadata for the files (and subdirectories) in the directory.
32#
33# Here's an example of a metadata file that uses three FileSet structures
34# (ignore the # characters):
35
36#<?xml version="1.0" encoding="UTF-8" standalone="no"?>
37#<!DOCTYPE DirectoryMetadata SYSTEM "http://greenstone.org/dtd/DirectoryMetadata/1.0/DirectoryMetadata.dtd">
38#<DirectoryMetadata>
39# <FileSet>
40# <FileName>nugget.*</FileName>
41# <Description>
42# <Metadata name="Title">Nugget Point, The Catlins</Metadata>
43# <Metadata name="Place" mode="accumulate">Nugget Point</Metadata>
44# </Description>
45# </FileSet>
46# <FileSet>
47# <FileName>nugget-point-1.jpg</FileName>
48# <Description>
49# <Metadata name="Title">Nugget Point Lighthouse, The Catlins</Metadata>
50# <Metadata name="Subject">Lighthouse</Metadata>
51# </Description>
52# </FileSet>
53# <FileSet>
54# <FileName>kaka-point-dir</FileName>
55# <Description>
56# <Metadata name="Title">Kaka Point, The Catlins</Metadata>
57# </Description>
58# </FileSet>
59#</DirectoryMetadata>
60
61# Metadata elements are read and applied to files in the order they appear
62# in the file.
63#
64# The FileName element describes the subfiles in the directory that the
65# metadata applies to as a perl regular expression (a FileSet group may
66# contain multiple FileName elements). So, <FileName>nugget.*</FileName>
67# indicates that the metadata records in the following Description block
68# apply to every subfile that starts with "nugget". For these files, a
69# Title metadata element is set, overriding any old value that the Title
70# might have had.
71#
72# Occasionally, we want to have multiple metadata values applied to a
73# document; in this case we use the "mode=accumulate" attribute of the
74# particular Metadata element. In the second metadata element of the first
75# FileSet above, the "Place" metadata is accumulating, and may therefore be
76# given several values. If we wanted to override these values and use a
77# single metadata element again, we could set the mode attribute to
78# "override" instead. Remember: every element is assumed to be in override
79# mode unless you specify otherwise, so if you want to accumulate metadata
80# for some field, every occurance must have "mode=accumulate" specified.
81#
82# The second FileSet element above applies to a specific file, called
83# nugget-point-1.jpg. This element overrides the Title metadata set in the
84# first FileSet, and adds a "Subject" metadata field.
85#
86# The third and final FileSet sets metadata for a subdirectory rather than
87# a file. The metadata specified (a Title) will be passed into the
88# subdirectory and applied to every file that occurs in the subdirectory
89# (and to every subsubdirectory and its contents, and so on) unless the
90# metadata is explictly overridden later in the import.
91
92
93
94package RecPlug;
95
96use BasPlug;
97use plugin;
98use util;
99
100use File::Basename;
101
102
103BEGIN {
104 @RecPlug::ISA = ('BasPlug');
105 unshift (@INC, "$ENV{'GSDLHOME'}/perllib/cpan");
106}
107
108use XMLParser;
109
110my $arguments =
111 [ { 'name' => "block_exp",
112 'desc' => "{BasPlug.block_exp}",
113 'type' => "regexp",
114 'deft' => &get_default_block_exp(),
115 'reqd' => "no" },
116 { 'name' => "use_metadata_files",
117 'desc' => "{RecPlug.use_metadata_files}",
118 'type' => "flag",
119 'reqd' => "no" },
120 { 'name' => "recheck_directories",
121 'desc' => "{RecPlug.recheck_directories}",
122 'type' => "flag",
123 'reqd' => "no" } ];
124
125my $options = { 'name' => "RecPlug",
126 'desc' => "{RecPlug.desc}",
127 'abstract' => "no",
128 'inherits' => "yes",
129 'args' => $arguments };
130
131
132my ($self);
133sub new {
134 my $class = shift (@_);
135
136 # $self is global for use within subroutines called by XML::Parser
137 $self = new BasPlug ($class, @_);
138
139 # 14-05-02 To allow for proper inheritance of arguments - John Thompson
140 my $option_list = $self->{'option_list'};
141 push( @{$option_list}, $options );
142
143 if (!parsargv::parse(\@_,
144 q^use_metadata_files^, \$self->{'use_metadata_files'},
145 q^recheck_directories^, \$self->{'recheck_directories'},
146 "allow_extra_options")) {
147 print STDERR "\nRecPlug uses an incorrect option.\n";
148 print STDERR "Check your collect.cfg configuration file.\n\n";
149 $self->print_txt_usage(""); # Use default resource bundle
150 die "\n";
151 }
152
153 if ($self->{'use_metadata_files'}) {
154 # create XML::Parser object for parsing metadata.xml files
155 my $parser = new XML::Parser('Style' => 'Stream',
156 'Handlers' => {'Char' => \&Char,
157 'Doctype' => \&Doctype
158 });
159 $self->{'parser'} = $parser;
160 $self->{'in_filename'} = 0;
161 }
162
163 $self->{'subdir_extrametakeys'} = {};
164
165 return bless $self, $class;
166}
167
168# return 1 if this class might recurse using $pluginfo
169sub is_recursive {
170 my $self = shift (@_);
171
172 return 1;
173}
174
175sub get_default_block_exp {
176 my $self = shift (@_);
177
178 return 'CVS';
179}
180
181# return number of files processed, undef if can't process
182# Note that $base_dir might be "" and that $file might
183# include directories
184
185# This function passes around metadata hash structures. Metadata hash
186# structures are hashes that map from a (scalar) key (the metadata element
187# name) to either a scalar metadata value or a reference to an array of
188# such values.
189
190sub read {
191 my $self = shift (@_);
192 my ($pluginfo, $base_dir, $file, $in_metadata, $processor, $maxdocs, $gli) = @_;
193
194 my $outhandle = $self->{'outhandle'};
195 my $verbosity = $self->{'verbosity'};
196 my $read_metadata_files = $self->{'use_metadata_files'};
197
198 # Calculate the directory name and ensure it is a directory and
199 # that it is not explicitly blocked.
200 my $dirname = $file;
201 $dirname = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
202 return undef unless (-d $dirname);
203 return 0 if ($self->{'block_exp'} ne "" && $dirname =~ /$self->{'block_exp'}/);
204
205 # check to make sure we're not reading the archives or index directory
206 my $gsdlhome = quotemeta($ENV{'GSDLHOME'});
207 if ($dirname =~ m/^$gsdlhome\/.*?\/import.*?\/(archives|index)$/) {
208 print $outhandle "RecPlug: $dirname appears to be a reference to a Greenstone collection, skipping.\n";
209 return 0;
210 }
211
212 # check to see we haven't got a cyclic path...
213 if ($dirname =~ m%(/.*){,41}%) {
214 print $outhandle "RecPlug: $dirname is 40 directories deep, is this a recursive path? if not increase constant in RecPlug.pm.\n";
215 return 0;
216 }
217
218 # check to see we haven't got a cyclic path...
219 if ($dirname =~ m%.*?import/(.+?)/import/\1.*%) {
220 print $outhandle "RecPlug: $dirname appears to be in a recursive loop...\n";
221 return 0;
222 }
223
224 if (($verbosity > 2) && ((scalar keys %$in_metadata) > 0)) {
225 print $outhandle "RecPlug: metadata passed in: ",
226 join(", ", keys %$in_metadata), "\n";
227 }
228
229 # Recur over directory contents.
230 my (@dir, $subfile);
231 my $count = 0;
232
233 print $outhandle "RecPlug: getting directory $dirname\n" if ($verbosity);
234
235 # find all the files in the directory
236 if (!opendir (DIR, $dirname)) {
237 print $outhandle "RecPlug: WARNING - couldn't read directory $dirname\n";
238 return -1; # error in processing
239 }
240 @dir = readdir (DIR);
241 closedir (DIR);
242
243 # Re-order the files in the list so any directories ending with .all are moved to the end
244 for (my $i = scalar(@dir) - 1; $i >= 0; $i--) {
245 if (-d &util::filename_cat($dirname, $dir[$i]) && $dir[$i] =~ /\.all$/) {
246 push(@dir, splice(@dir, $i, 1));
247 }
248 }
249
250 # read XML metadata files (if supplied)
251 my $additionalmetadata = 0; # is there extra metadata available?
252 my %extrametadata; # maps from filespec to extra metadata keys
253 my @extrametakeys; # keys of %extrametadata in order read
254
255 my $dirsepre = &util::get_re_dirsep();
256 my $dirsep = &util::get_dirsep();
257 my $local_dirname = $dirname;
258 $local_dirname =~ s/^$base_dir($dirsepre)//;
259 $local_dirname .= $dirsep;
260
261 if (defined $self->{'subdir_extrametakeys'}->{$local_dirname}) {
262 my $extrakeys = $self->{'subdir_extrametakeys'}->{$local_dirname};
263 foreach my $ek (@$extrakeys) {
264 my $extrakeys_re = $ek->{'re'};
265 my $extrakeys_md = $ek->{'md'};
266 push(@extrametakeys,$extrakeys_re);
267 $extrametadata{$extrakeys_re} = $extrakeys_md;
268 }
269 delete($self->{'subdir_extrametakeys'}->{$local_dirname});
270 }
271
272 if ($read_metadata_files) {
273 #read the directory "metadata.xml" file
274 my $metadatafile = &util::filename_cat ($dirname, 'metadata.xml');
275 if (-e $metadatafile) {
276 print $outhandle "RecPlug: found metadata in $metadatafile\n"
277 if ($verbosity);
278 $self->read_metadata_xml_file($metadatafile, \%extrametadata, \@extrametakeys);
279 $additionalmetadata = 1;
280 }
281 }
282
283 # apply metadata pass for each of the files in the directory
284 my $out_metadata;
285 my $num_files = scalar(@dir);
286 for (my $i = 0; $i < scalar(@dir); $i++) {
287 my $subfile = $dir[$i];
288 my $this_file_base_dir = $base_dir;
289 last if ($maxdocs != -1 && $count >= $maxdocs);
290 next if ($subfile =~ m/^\.\.?$/);
291 #next if ($read_metadata_files && $subfile =~ /metadata\.xml$/);
292
293 # Recursively read each $subfile
294 print $outhandle "RecPlug metadata recurring: $subfile\n" if ($verbosity > 2);
295
296 $count += &plugin::metadata_read ($pluginfo, $this_file_base_dir,
297 &util::filename_cat($file, $subfile),
298 $out_metadata, \@extrametakeys, \%extrametadata,
299 $processor, $maxdocs, $gli);
300 $additionalmetadata = 1;
301 }
302
303 # filter out any extrametakeys that mention subdirectories and store
304 # for later use (i.e. when that sub-directory is being processed)
305
306 foreach my $ek (@extrametakeys) {
307 my ($subdir_re,$extrakey_dir) = &File::Basename::fileparse($ek);
308 $extrakey_dir =~ s/\\\./\./g; # remove RE syntax
309
310 my $dirsep_re = &util::get_re_dirsep();
311
312 if ($ek =~ m/$dirsep_re/) { # specifies at least one directory
313 my $md = $extrametadata{$ek};
314
315 my $subdir_extrametakeys = $self->{'subdir_extrametakeys'};
316
317 my $subdir_rec = { 're' => $subdir_re, 'md' => $md };
318 push(@{$subdir_extrametakeys->{$extrakey_dir}},$subdir_rec);
319 }
320 }
321
322 # import each of the files in the directory
323 $count=0;
324 for (my $i = 0; $i <= scalar(@dir); $i++) {
325 # When every file in the directory has been done, pause for a moment (figuratively!)
326 # If the -recheck_directories argument hasn't been provided, stop now (default)
327 # Otherwise, re-read the contents of the directory to check for new files
328 # Any new files are added to the @dir list and are processed as normal
329 # This is necessary when documents to be indexed are specified in bibliographic DBs
330 # These files are copied/downloaded and stored in a new folder at import time
331 if ($i == $num_files) {
332 last unless $self->{'recheck_directories'};
333
334 # Re-read the files in the directory to see if there are any new files
335 last if (!opendir (DIR, $dirname));
336 my @dirnow = readdir (DIR);
337 closedir (DIR);
338
339 # We're only interested if there are more files than there were before
340 last if (scalar(@dirnow) <= scalar(@dir));
341
342 # Any new files are added to the end of @dir to get processed by the loop
343 my $j;
344 foreach my $subfilenow (@dirnow) {
345 for ($j = 0; $j < $num_files; $j++) {
346 last if ($subfilenow eq $dir[$j]);
347 }
348 if ($j == $num_files) {
349 # New file
350 push(@dir, $subfilenow);
351 }
352 }
353 # When the new files have been processed, check again
354 $num_files = scalar(@dir);
355 }
356
357 my $subfile = $dir[$i];
358 my $this_file_base_dir = $base_dir;
359 last if ($maxdocs != -1 && $count >= $maxdocs);
360 next if ($subfile =~ /^\.\.?$/);
361 next if ($read_metadata_files && $subfile =~ /metadata\.xml$/);
362
363 # Follow Windows shortcuts
364 if ($subfile =~ /(?i)\.lnk$/ && $ENV{'GSDLOS'} =~ /^windows$/i) {
365 require Win32::Shortcut;
366 my $shortcut = new Win32::Shortcut(&util::filename_cat($dirname, $subfile));
367 if ($shortcut) {
368 # The file to be processed is now the target of the shortcut
369 $this_file_base_dir = "";
370 $file = "";
371 $subfile = $shortcut->Path;
372 }
373 }
374
375 # check for a symlink pointing back to a leading directory
376 if (-d "$dirname/$subfile" && -l "$dirname/$subfile") {
377 # readlink gives a "fatal error" on systems that don't implement
378 # symlinks. This assumes the the -l test above would fail on those.
379 my $linkdest=readlink "$dirname/$subfile";
380 if (!defined ($linkdest)) {
381 # system error - file not found?
382 warn "RecPlug: symlink problem - $!";
383 } else {
384 # see if link points to current or a parent directory
385 if ($linkdest =~ m@^[\./\\]+$@ ||
386 index($dirname, $linkdest) != -1) {
387 warn "RecPlug: Ignoring recursive symlink ($dirname/$subfile -> $linkdest)\n";
388 next;
389 ;
390 }
391 }
392 }
393
394 print $outhandle "RecPlug: preparing metadata for $subfile\n" if ($verbosity > 2);
395
396 # Make a copy of $in_metadata to pass to $subfile
397 $out_metadata = {};
398 &combine_metadata_structures($out_metadata, $in_metadata);
399
400 # Next add metadata read in XML files (if it is supplied)
401 if ($additionalmetadata == 1) {
402 my ($filespec, $mdref);
403 foreach $filespec (@extrametakeys) {
404 if ($subfile =~ /^$filespec$/) {
405 print $outhandle "File \"$subfile\" matches filespec \"$filespec\"\n"
406 if ($verbosity > 2);
407 $mdref = $extrametadata{$filespec};
408 &combine_metadata_structures($out_metadata, $mdref);
409 }
410 }
411 }
412
413 # Recursively read each $subfile
414 print $outhandle "RecPlug recurring: $subfile\n" if ($verbosity > 2);
415
416 $count += &plugin::read ($pluginfo, $this_file_base_dir,
417 &util::filename_cat($file, $subfile),
418 $out_metadata, $processor, $maxdocs, $gli);
419 }
420
421 return $count;
422}
423
424
425
426# Read a manually-constructed metadata file and store the data
427# it contains in the $metadataref structure.
428#
429# (metadataref is a reference to a hash whose keys are filenames
430# and whose values are metadata hash structures.)
431
432sub read_metadata_xml_file {
433 my $self = shift(@_);
434 my ($filename, $metadataref, $metakeysref) = @_;
435 $self->{'metadataref'} = $metadataref;
436 $self->{'metakeysref'} = $metakeysref;
437
438 eval {
439 $self->{'parser'}->parsefile($filename);
440 };
441
442 if ($@) {
443 die "RecPlug: ERROR $filename is not a well formed metadata.xml file ($@)\n";
444 }
445}
446
447sub Doctype {
448 my ($expat, $name, $sysid, $pubid, $internal) = @_;
449
450 # allow the short-lived and badly named "GreenstoneDirectoryMetadata" files
451 # to be processed as well as the "DirectoryMetadata" files which should now
452 # be created by import.pl
453 die if ($name !~ /^(Greenstone)?DirectoryMetadata$/);
454}
455
456sub StartTag {
457 my ($expat, $element) = @_;
458
459 if ($element eq "FileSet") {
460 $self->{'saved_targets'} = [];
461 $self->{'saved_metadata'} = {};
462 }
463 elsif ($element eq "FileName") {
464 $self->{'in_filename'} = 1;
465 }
466 elsif ($element eq "Metadata") {
467 $self->{'metadata_name'} = $_{'name'};
468 if ((defined $_{'mode'}) && ($_{'mode'} eq "accumulate")) {
469 $self->{'metadata_accumulate'} = 1;
470 } else {
471 $self->{'metadata_accumulate'} = 0;
472 }
473 }
474}
475
476sub EndTag {
477 my ($expat, $element) = @_;
478
479 if ($element eq "FileSet") {
480 push (@{$self->{'metakeysref'}}, @{$self->{'saved_targets'}});
481 foreach my $target (@{$self->{'saved_targets'}}) {
482 my $file_metadata = $self->{'metadataref'}->{$target};
483 my $saved_metadata = $self->{'saved_metadata'};
484 if (!defined $file_metadata) {
485 $self->{'metadataref'}->{$target} = $saved_metadata;
486 }
487 else {
488 $self->combine_metadata_structures($file_metadata,$saved_metadata);
489 }
490 }
491 }
492 elsif ($element eq "FileName") {
493 $self->{'in_filename'} = 0;
494 }
495 elsif ($element eq "Metadata") {
496 $self->{'metadata_name'} = "";
497 }
498
499}
500
501sub store_saved_metadata
502{
503 my $self = shift(@_);
504 my ($mname,$mvalue,$md_accumulate) = @_;
505
506 if (defined $self->{'saved_metadata'}->{$mname}) {
507 if ($md_accumulate) {
508 # accumulate mode - add value to existing value(s)
509 if (ref ($self->{'saved_metadata'}->{$mname}) eq "ARRAY") {
510 push (@{$self->{'saved_metadata'}->{$mname}}, $mvalue);
511 } else {
512 $self->{'saved_metadata'}->{$mname} =
513 [$self->{'saved_metadata'}->{$mname}, $mvalue];
514 }
515 } else {
516 # override mode
517 $self->{'saved_metadata'}->{$mname} = $mvalue;
518 }
519 } else {
520 if ($md_accumulate) {
521 # accumulate mode - add value into (currently empty) array
522 $self->{'saved_metadata'}->{$mname} = [$mvalue];
523 } else {
524 # override mode
525 $self->{'saved_metadata'}->{$mname} = $mvalue;
526 }
527 }
528}
529
530
531sub Text {
532
533 if ($self->{'in_filename'}) {
534 # $_ == FileName content
535 push (@{$self->{'saved_targets'}}, $_);
536 }
537 elsif (defined ($self->{'metadata_name'}) && $self->{'metadata_name'} ne "") {
538 # $_ == Metadata content
539 my $mname = $self->{'metadata_name'};
540 my $mvalue = $_;
541 my $md_accumulate = $self->{'metadata_accumulate'};
542 $self->store_saved_metadata($mname,$mvalue,$md_accumulate);
543 }
544}
545
546# This Char function overrides the one in XML::Parser::Stream to overcome a
547# problem where $expat->{Text} is treated as the return value, slowing
548# things down significantly in some cases.
549sub Char {
550 use bytes; # Necessary to prevent encoding issues with XML::Parser 2.31+
551 $_[0]->{'Text'} .= $_[1];
552 return undef;
553}
554
555# Combine two metadata structures. Given two references to metadata
556# element structures, add every field of the second ($mdref2) to the first
557# ($mdref1).
558#
559# Afterwards $mdref1 will be updated, and $mdref2 will be unchanged.
560#
561# We have to be careful about the way we merge metadata when one metadata
562# structure is in "override" mode and one is in "merge" mode. In fact, we
563# use the mode from the second structure, $mdref2, because it is generally
564# defined later (lower in the directory structure) and is therefore more
565# "local" to the document concerned.
566#
567# Another issue is the use of references to pass metadata around. If we
568# simply copy one metadata structure reference to another, then we're
569# effectively just copyinga pointer, and changes to the new referene
570# will affect the old (copied) one also. This also applies to ARRAY
571# references used as metadata element values (hence the "clonedata"
572# function below).
573
574sub combine_metadata_structures {
575 my ($mdref1, $mdref2) = @_;
576 my ($key, $value1, $value2);
577
578 foreach $key (keys %$mdref2) {
579
580 $value1 = $mdref1->{$key};
581 $value2 = $mdref2->{$key};
582
583 # If there is no existing value for this metadata field in
584 # $mdref1, so we simply copy the value from $mdref2 over.
585 if (!defined $value1) {
586 $mdref1->{$key} = &clonedata($value2);
587 }
588 # Otherwise we have to add the new values to the existing ones.
589 # If the second structure is accumulated, then acculate all the
590 # values into the first structure
591 elsif ((ref $value2) eq "ARRAY") {
592 # If the first metadata element is a scalar we have to
593 # convert it into an array before we add anything more.
594 if ((ref $value1) ne 'ARRAY') {
595 $mdref1->{$key} = [$value1];
596 $value1 = $mdref1->{$key};
597 }
598 # Now add the value(s) from the second array to the first
599 $value2 = &clonedata($value2);
600 push @$value1, @$value2;
601 }
602 # Finally, If the second structure is not an array erference, we
603 # know it is in override mode, so override the first structure.
604 else {
605 $mdref1->{$key} = &clonedata($value2);
606 }
607 }
608}
609
610
611# Make a "cloned" copy of a metadata value.
612# This is trivial for a simple scalar value,
613# but not for an array reference.
614
615sub clonedata {
616 my ($value) = @_;
617 my $result;
618
619 if ((ref $value) eq 'ARRAY') {
620 $result = [];
621 foreach my $item (@$value) {
622 push @$result, $item;
623 }
624 } else {
625 $result = $value;
626 }
627 return $result;
628}
629
630
6311;
Note: See TracBrowser for help on using the repository browser.