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

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

Grrr... why doesn't anyone think about Windows when writing code?

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 20.1 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 print STDERR "**** Matching on dirname = $local_dirname\n";
263 my $extrakeys = $self->{'subdir_extrametakeys'}->{$local_dirname};
264 foreach my $ek (@$extrakeys) {
265 my $extrakeys_re = $ek->{'re'};
266 my $extrakeys_md = $ek->{'md'};
267 push(@extrametakeys,$extrakeys_re);
268 $extrametadata{$extrakeys_re} = $extrakeys_md;
269 }
270 delete($self->{'subdir_extrametakeys'}->{$local_dirname});
271 }
272
273 if ($read_metadata_files) {
274 #read the directory "metadata.xml" file
275 my $metadatafile = &util::filename_cat ($dirname, 'metadata.xml');
276 if (-e $metadatafile) {
277 print $outhandle "RecPlug: found metadata in $metadatafile\n"
278 if ($verbosity);
279 $self->read_metadata_xml_file($metadatafile, \%extrametadata, \@extrametakeys);
280 $additionalmetadata = 1;
281 }
282 }
283
284 # import each of the files in the directory
285 my $out_metadata;
286 my $num_files = scalar(@dir);
287 for (my $i = 0; $i < scalar(@dir); $i++) {
288 my $subfile = $dir[$i];
289 my $this_file_base_dir = $base_dir;
290 last if ($maxdocs != -1 && $count >= $maxdocs);
291 next if ($subfile =~ /^\.\.?$/);
292 #next if ($read_metadata_files && $subfile =~ /metadata\.xml$/);
293
294 # Recursively read each $subfile
295 print $outhandle "RecPlug metadata recurring: $subfile\n" if ($verbosity > 2);
296
297 $count += &plugin::metadata_read ($pluginfo, $this_file_base_dir,
298 &util::filename_cat($file, $subfile),
299 $out_metadata, \@extrametakeys, \%extrametadata,
300 $processor, $maxdocs, $gli);
301 $additionalmetadata = 1;
302 }
303
304 # filter out any extrametakeys that mention subdirectories and store
305 # for later use (i.e. when that sub-directory is being processed)
306
307 foreach my $ek (@extrametakeys) {
308 my ($subdir_re,$extrakey_dir) = &File::Basename::fileparse($ek);
309 $extrakey_dir =~ s/\\\./\./g; # remove RE syntax
310
311 my $dirsep_re = &util::get_re_dirsep();
312
313 if ($ek =~ m/$dirsep_re/) { # specifies at least one directory
314 my $md = $extrametadata{$ek};
315
316 my $subdir_extrametakeys = $self->{'subdir_extrametakeys'};
317 print STDERR "*** pushing on $subdir_re for $extrakey_dir\n";
318
319 my $subdir_rec = { 're' => $subdir_re, 'md' => $md };
320 push(@{$subdir_extrametakeys->{$extrakey_dir}},$subdir_rec);
321 }
322 }
323
324 # import each of the files in the directory
325 $count=0;
326 for (my $i = 0; $i <= scalar(@dir); $i++) {
327 # When every file in the directory has been done, pause for a moment (figuratively!)
328 # If the -recheck_directories argument hasn't been provided, stop now (default)
329 # Otherwise, re-read the contents of the directory to check for new files
330 # Any new files are added to the @dir list and are processed as normal
331 # This is necessary when documents to be indexed are specified in bibliographic DBs
332 # These files are copied/downloaded and stored in a new folder at import time
333 if ($i == $num_files) {
334 last unless $self->{'recheck_directories'};
335
336 # Re-read the files in the directory to see if there are any new files
337 last if (!opendir (DIR, $dirname));
338 my @dirnow = readdir (DIR);
339 closedir (DIR);
340
341 # We're only interested if there are more files than there were before
342 last if (scalar(@dirnow) <= scalar(@dir));
343
344 # Any new files are added to the end of @dir to get processed by the loop
345 my $j;
346 foreach my $subfilenow (@dirnow) {
347 for ($j = 0; $j < $num_files; $j++) {
348 last if ($subfilenow eq $dir[$j]);
349 }
350 if ($j == $num_files) {
351 # New file
352 push(@dir, $subfilenow);
353 }
354 }
355 # When the new files have been processed, check again
356 $num_files = scalar(@dir);
357 }
358
359 my $subfile = $dir[$i];
360 my $this_file_base_dir = $base_dir;
361 last if ($maxdocs != -1 && $count >= $maxdocs);
362 next if ($subfile =~ /^\.\.?$/);
363 next if ($read_metadata_files && $subfile =~ /metadata\.xml$/);
364
365 # Follow Windows shortcuts
366 if ($subfile =~ /(?i)\.lnk$/ && $ENV{'GSDLOS'} =~ /^windows$/i) {
367 require Win32::Shortcut;
368 my $shortcut = new Win32::Shortcut(&util::filename_cat($dirname, $subfile));
369 if ($shortcut) {
370 # The file to be processed is now the target of the shortcut
371 $this_file_base_dir = "";
372 $file = "";
373 $subfile = $shortcut->Path;
374 }
375 }
376
377 # check for a symlink pointing back to a leading directory
378 if (-d "$dirname/$subfile" && -l "$dirname/$subfile") {
379 # readlink gives a "fatal error" on systems that don't implement
380 # symlinks. This assumes the the -l test above would fail on those.
381 my $linkdest=readlink "$dirname/$subfile";
382 if (!defined ($linkdest)) {
383 # system error - file not found?
384 warn "RecPlug: symlink problem - $!";
385 } else {
386 # see if link points to current or a parent directory
387 if ($linkdest =~ m@^[\./\\]+$@ ||
388 index($dirname, $linkdest) != -1) {
389 warn "RecPlug: Ignoring recursive symlink ($dirname/$subfile -> $linkdest)\n";
390 next;
391 ;
392 }
393 }
394 }
395
396 print $outhandle "RecPlug: preparing metadata for $subfile\n" if ($verbosity > 2);
397
398 # Make a copy of $in_metadata to pass to $subfile
399 $out_metadata = {};
400 &combine_metadata_structures($out_metadata, $in_metadata);
401
402 # Next add metadata read in XML files (if it is supplied)
403 if ($additionalmetadata == 1) {
404 my ($filespec, $mdref);
405 foreach $filespec (@extrametakeys) {
406 if ($subfile =~ /^$filespec$/) {
407 print $outhandle "File \"$subfile\" matches filespec \"$filespec\"\n"
408 if ($verbosity > 2);
409 $mdref = $extrametadata{$filespec};
410 &combine_metadata_structures($out_metadata, $mdref);
411 }
412 }
413 }
414
415 # Recursively read each $subfile
416 print $outhandle "RecPlug recurring: $subfile\n" if ($verbosity > 2);
417
418 $count += &plugin::read ($pluginfo, $this_file_base_dir,
419 &util::filename_cat($file, $subfile),
420 $out_metadata, $processor, $maxdocs, $gli);
421 }
422
423 return $count;
424}
425
426
427
428# Read a manually-constructed metadata file and store the data
429# it contains in the $metadataref structure.
430#
431# (metadataref is a reference to a hash whose keys are filenames
432# and whose values are metadata hash structures.)
433
434sub read_metadata_xml_file {
435 my $self = shift(@_);
436 my ($filename, $metadataref, $metakeysref) = @_;
437 $self->{'metadataref'} = $metadataref;
438 $self->{'metakeysref'} = $metakeysref;
439
440 eval {
441 $self->{'parser'}->parsefile($filename);
442 };
443
444 if ($@) {
445 die "RecPlug: ERROR $filename is not a well formed metadata.xml file ($@)\n";
446 }
447}
448
449sub Doctype {
450 my ($expat, $name, $sysid, $pubid, $internal) = @_;
451
452 # allow the short-lived and badly named "GreenstoneDirectoryMetadata" files
453 # to be processed as well as the "DirectoryMetadata" files which should now
454 # be created by import.pl
455 die if ($name !~ /^(Greenstone)?DirectoryMetadata$/);
456}
457
458sub StartTag {
459 my ($expat, $element) = @_;
460
461 if ($element eq "FileSet") {
462 $self->{'saved_targets'} = [];
463 $self->{'saved_metadata'} = {};
464 }
465 elsif ($element eq "FileName") {
466 $self->{'in_filename'} = 1;
467 }
468 elsif ($element eq "Metadata") {
469 $self->{'metadata_name'} = $_{'name'};
470 if ((defined $_{'mode'}) && ($_{'mode'} eq "accumulate")) {
471 $self->{'metadata_accumulate'} = 1;
472 } else {
473 $self->{'metadata_accumulate'} = 0;
474 }
475 }
476}
477
478sub EndTag {
479 my ($expat, $element) = @_;
480
481 if ($element eq "FileSet") {
482 push (@{$self->{'metakeysref'}}, @{$self->{'saved_targets'}});
483 foreach my $target (@{$self->{'saved_targets'}}) {
484 $self->{'metadataref'}->{$target} = $self->{'saved_metadata'};
485 }
486 }
487 elsif ($element eq "FileName") {
488 $self->{'in_filename'} = 0;
489 }
490 elsif ($element eq "Metadata") {
491 $self->{'metadata_name'} = "";
492 }
493
494}
495
496sub Text {
497
498 if ($self->{'in_filename'}) {
499 # $_ == FileName content
500 push (@{$self->{'saved_targets'}}, $_);
501 }
502 elsif (defined ($self->{'metadata_name'}) && $self->{'metadata_name'} ne "") {
503 # $_ == Metadata content
504 my $mname = $self->{'metadata_name'};
505 if (defined $self->{'saved_metadata'}->{$mname}) {
506 if ($self->{'metadata_accumulate'}) {
507 # accumulate mode - add value to existing value(s)
508 if (ref ($self->{'saved_metadata'}->{$mname}) eq "ARRAY") {
509 push (@{$self->{'saved_metadata'}->{$mname}}, $_);
510 } else {
511 $self->{'saved_metadata'}->{$mname} =
512 [$self->{'saved_metadata'}->{$mname}, $_];
513 }
514 } else {
515 # override mode
516 $self->{'saved_metadata'}->{$mname} = $_;
517 }
518 } else {
519 if ($self->{'metadata_accumulate'}) {
520 # accumulate mode - add value into (currently empty) array
521 $self->{'saved_metadata'}->{$mname} = [$_];
522 } else {
523 # override mode
524 $self->{'saved_metadata'}->{$mname} = $_;
525 }
526 }
527 }
528}
529
530# This Char function overrides the one in XML::Parser::Stream to overcome a
531# problem where $expat->{Text} is treated as the return value, slowing
532# things down significantly in some cases.
533sub Char {
534 $_[0]->{'Text'} .= $_[1];
535 return undef;
536}
537
538# Combine two metadata structures. Given two references to metadata
539# element structures, add every field of the second ($mdref2) to the first
540# ($mdref1).
541#
542# Afterwards $mdref1 will be updated, and $mdref2 will be unchanged.
543#
544# We have to be careful about the way we merge metadata when one metadata
545# structure is in "override" mode and one is in "merge" mode. In fact, we
546# use the mode from the second structure, $mdref2, because it is generally
547# defined later (lower in the directory structure) and is therefore more
548# "local" to the document concerned.
549#
550# Another issue is the use of references to pass metadata around. If we
551# simply copy one metadata structure reference to another, then we're
552# effectively just copyinga pointer, and changes to the new referene
553# will affect the old (copied) one also. This also applies to ARRAY
554# references used as metadata element values (hence the "clonedata"
555# function below).
556
557sub combine_metadata_structures {
558 my ($mdref1, $mdref2) = @_;
559 my ($key, $value1, $value2);
560
561 foreach $key (keys %$mdref2) {
562
563 $value1 = $mdref1->{$key};
564 $value2 = $mdref2->{$key};
565
566 # If there is no existing value for this metadata field in
567 # $mdref1, so we simply copy the value from $mdref2 over.
568 if (!defined $value1) {
569 $mdref1->{$key} = &clonedata($value2);
570 }
571 # Otherwise we have to add the new values to the existing ones.
572 # If the second structure is accumulated, then acculate all the
573 # values into the first structure
574 elsif ((ref $value2) eq "ARRAY") {
575 # If the first metadata element is a scalar we have to
576 # convert it into an array before we add anything more.
577 if ((ref $value1) ne 'ARRAY') {
578 $mdref1->{$key} = [$value1];
579 $value1 = $mdref1->{$key};
580 }
581 # Now add the value(s) from the second array to the first
582 $value2 = &clonedata($value2);
583 push @$value1, @$value2;
584 }
585 # Finally, If the second structure is not an array erference, we
586 # know it is in override mode, so override the first structure.
587 else {
588 $mdref1->{$key} = &clonedata($value2);
589 }
590 }
591}
592
593
594# Make a "cloned" copy of a metadata value.
595# This is trivial for a simple scalar value,
596# but not for an array reference.
597
598sub clonedata {
599 my ($value) = @_;
600 my $result;
601
602 if ((ref $value) eq 'ARRAY') {
603 $result = [];
604 foreach my $item (@$value) {
605 push @$result, $item;
606 }
607 } else {
608 $result = $value;
609 }
610 return $result;
611}
612
613
6141;
Note: See TracBrowser for help on using the repository browser.