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

Last change on this file since 14180 was 14180, checked in by mdewsnip, 14 years ago

Now ignores .svn directories as well as CVS directories.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 15.6 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;
99use metadatautil;
100
101use File::Basename;
102use strict;
103no strict 'refs';
104use Encode;
105
106BEGIN {
107 @RecPlug::ISA = ('BasPlug');
108}
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 # this option has been deprecated. leave it here for now so we can warn people not to use it
117 { 'name' => "use_metadata_files",
118 'desc' => "{RecPlug.use_metadata_files}",
119 'type' => "flag",
120 'reqd' => "no",
121 'hiddengli' => "yes" },
122 { 'name' => "recheck_directories",
123 'desc' => "{RecPlug.recheck_directories}",
124 'type' => "flag",
125 'reqd' => "no" } ];
126
127my $options = { 'name' => "RecPlug",
128 'desc' => "{RecPlug.desc}",
129 'abstract' => "no",
130 'inherits' => "yes",
131 'args' => $arguments };
132
133sub new {
134 my ($class) = shift (@_);
135 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
136 push(@$pluginlist, $class);
137
138 if(defined $arguments){ push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});}
139 if(defined $options) { push(@{$hashArgOptLists->{"OptList"}},$options)};
140
141 my $self = new BasPlug($pluginlist, $inputargs, $hashArgOptLists);
142
143 if ($self->{'info_only'}) {
144 # don't worry about any options or initialisations etc
145 return bless $self, $class;
146 }
147
148 # we have left this option in so we can warn people who are still using it
149 if ($self->{'use_metadata_files'}) {
150 die "ERROR: RecPlug -use_metadata_files option has been deprecated. Please remove the option and add MetadataXMLPlug to your plugin list instead!\n";
151 }
152
153 $self->{'subdir_extrametakeys'} = {};
154
155 return bless $self, $class;
156}
157
158sub begin {
159 my $self = shift (@_);
160 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
161
162 my $proc_package_name = ref $processor;
163
164 if ($proc_package_name !~ /buildproc$/ && $self->{'incremental'} == 1) {
165
166 # Only lookup timestamp info for import.pl, and only if incremental is set
167
168 my $output_dir = $processor->getoutputdir();
169 my $archives_inf = &util::filename_cat($output_dir,"archives.inf");
170
171 if ( -e $archives_inf ) {
172 $self->{'inf_timestamp'} = -M $archives_inf;
173 }
174 }
175
176 $self->SUPER::begin($pluginfo, $base_dir, $processor, $maxdocs);
177}
178
179
180# return 1 if this class might recurse using $pluginfo
181sub is_recursive {
182 my $self = shift (@_);
183
184 return 1;
185}
186
187sub get_default_block_exp {
188 my $self = shift (@_);
189
190 return '(CVS|\.svn)';
191}
192
193# return number of files processed, undef if can't process
194# Note that $base_dir might be "" and that $file might
195# include directories
196
197# This function passes around metadata hash structures. Metadata hash
198# structures are hashes that map from a (scalar) key (the metadata element
199# name) to either a scalar metadata value or a reference to an array of
200# such values.
201
202sub read {
203 my $self = shift (@_);
204 my ($pluginfo, $base_dir, $file, $in_metadata, $processor, $maxdocs, $total_count, $gli) = @_;
205
206 my $outhandle = $self->{'outhandle'};
207 my $verbosity = $self->{'verbosity'};
208 my $read_metadata_files = $self->{'use_metadata_files'};
209
210 # Calculate the directory name and ensure it is a directory and
211 # that it is not explicitly blocked.
212 my $dirname = $file;
213 $dirname = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
214 return undef unless (-d $dirname);
215 return 0 if ($self->{'block_exp'} ne "" && $dirname =~ /$self->{'block_exp'}/);
216
217 # check to make sure we're not reading the archives or index directory
218 my $gsdlhome = quotemeta($ENV{'GSDLHOME'});
219 if ($dirname =~ m/^$gsdlhome\/.*?\/import.*?\/(archives|index)$/) {
220 print $outhandle "RecPlug: $dirname appears to be a reference to a Greenstone collection, skipping.\n";
221 return 0;
222 }
223
224 # check to see we haven't got a cyclic path...
225 if ($dirname =~ m%(/.*){,41}%) {
226 print $outhandle "RecPlug: $dirname is 40 directories deep, is this a recursive path? if not increase constant in RecPlug.pm.\n";
227 return 0;
228 }
229
230 # check to see we haven't got a cyclic path...
231 if ($dirname =~ m%.*?import/(.+?)/import/\1.*%) {
232 print $outhandle "RecPlug: $dirname appears to be in a recursive loop...\n";
233 return 0;
234 }
235
236 if (($verbosity > 2) && ((scalar keys %$in_metadata) > 0)) {
237 print $outhandle "RecPlug: metadata passed in: ",
238 join(", ", keys %$in_metadata), "\n";
239 }
240
241 # Recur over directory contents.
242 my (@dir, $subfile);
243 my $count = 0;
244
245 print $outhandle "RecPlug: getting directory $dirname\n" if ($verbosity);
246
247 # find all the files in the directory
248 if (!opendir (DIR, $dirname)) {
249 if ($gli) {
250 print STDERR "<ProcessingError n='$file' r='Could not read directory $dirname'>\n";
251 }
252 print $outhandle "RecPlug: WARNING - couldn't read directory $dirname\n";
253 return -1; # error in processing
254 }
255 @dir = readdir (DIR);
256 closedir (DIR);
257
258 # Re-order the files in the list so any directories ending with .all are moved to the end
259 for (my $i = scalar(@dir) - 1; $i >= 0; $i--) {
260 if (-d &util::filename_cat($dirname, $dir[$i]) && $dir[$i] =~ /\.all$/) {
261 push(@dir, splice(@dir, $i, 1));
262 }
263 }
264
265 # setup the metadata structures. we do a metadata_read pass to see if there is any additional metadata, then pass it to read
266
267 my $additionalmetadata = 0; # is there extra metadata available?
268 my %extrametadata; # maps from filespec to extra metadata keys
269 my @extrametakeys; # keys of %extrametadata in order read
270
271 my $os_dirsep = &util::get_os_dirsep();
272 my $dirsep = &util::get_dirsep();
273 my $base_dir_regexp = $base_dir;
274 $base_dir_regexp =~ s/\//$os_dirsep/g;
275 my $local_dirname = $dirname;
276 $local_dirname =~ s/^$base_dir_regexp($os_dirsep)//;
277 $local_dirname .= $dirsep;
278
279 if (defined $self->{'subdir_extrametakeys'}->{$local_dirname}) {
280 my $extrakeys = $self->{'subdir_extrametakeys'}->{$local_dirname};
281 foreach my $ek (@$extrakeys) {
282 my $extrakeys_re = $ek->{'re'};
283 my $extrakeys_md = $ek->{'md'};
284 push(@extrametakeys,$extrakeys_re);
285 $extrametadata{$extrakeys_re} = $extrakeys_md;
286 }
287 delete($self->{'subdir_extrametakeys'}->{$local_dirname});
288 }
289
290 # apply metadata pass for each of the files in the directory
291 my $out_metadata;
292 my $num_files = scalar(@dir);
293 for (my $i = 0; $i < scalar(@dir); $i++) {
294 my $subfile = $dir[$i];
295 my $this_file_base_dir = $base_dir;
296 last if ($maxdocs != -1 && $count >= $maxdocs);
297 next if ($subfile =~ m/^\.\.?$/);
298
299 # Recursively read each $subfile
300 print $outhandle "RecPlug metadata recurring: $subfile\n" if ($verbosity > 2);
301
302 $count += &plugin::metadata_read ($pluginfo, $this_file_base_dir,
303 &util::filename_cat($file, $subfile),
304 $out_metadata, \@extrametakeys, \%extrametadata,
305 $processor, $maxdocs, $gli);
306 $additionalmetadata = 1;
307 }
308
309 # filter out any extrametakeys that mention subdirectories and store
310 # for later use (i.e. when that sub-directory is being processed)
311
312 foreach my $ek (@extrametakeys) {
313 my ($subdir_re,$extrakey_dir) = &File::Basename::fileparse($ek);
314 $extrakey_dir =~ s/\\\./\./g; # remove RE syntax
315
316 my $dirsep_re = &util::get_re_dirsep();
317 if ($ek =~ m/$dirsep_re/) { # specifies at least one directory
318 my $md = $extrametadata{$ek};
319
320 my $subdir_extrametakeys = $self->{'subdir_extrametakeys'};
321
322 my $subdir_rec = { 're' => $subdir_re, 'md' => $md };
323 push(@{$subdir_extrametakeys->{$extrakey_dir}},$subdir_rec);
324 }
325 }
326
327 # import each of the files in the directory
328 $count=0;
329 for (my $i = 0; $i <= scalar(@dir); $i++) {
330 # When every file in the directory has been done, pause for a moment (figuratively!)
331 # If the -recheck_directories argument hasn't been provided, stop now (default)
332 # Otherwise, re-read the contents of the directory to check for new files
333 # Any new files are added to the @dir list and are processed as normal
334 # This is necessary when documents to be indexed are specified in bibliographic DBs
335 # These files are copied/downloaded and stored in a new folder at import time
336 if ($i == $num_files) {
337 last unless $self->{'recheck_directories'};
338
339 # Re-read the files in the directory to see if there are any new files
340 last if (!opendir (DIR, $dirname));
341 my @dirnow = readdir (DIR);
342 closedir (DIR);
343
344 # We're only interested if there are more files than there were before
345 last if (scalar(@dirnow) <= scalar(@dir));
346
347 # Any new files are added to the end of @dir to get processed by the loop
348 my $j;
349 foreach my $subfilenow (@dirnow) {
350 for ($j = 0; $j < $num_files; $j++) {
351 last if ($subfilenow eq $dir[$j]);
352 }
353 if ($j == $num_files) {
354 # New file
355 push(@dir, $subfilenow);
356 }
357 }
358 # When the new files have been processed, check again
359 $num_files = scalar(@dir);
360 }
361
362 my $subfile = $dir[$i];
363 my $this_file_base_dir = $base_dir;
364 last if ($maxdocs != -1 && ($count + $total_count) >= $maxdocs);
365 next if ($subfile =~ /^\.\.?$/);
366
367 # Follow Windows shortcuts
368 if ($subfile =~ /(?i)\.lnk$/ && $ENV{'GSDLOS'} =~ /^windows$/i) {
369 require Win32::Shortcut;
370 my $shortcut = new Win32::Shortcut(&util::filename_cat($dirname, $subfile));
371 if ($shortcut) {
372 # The file to be processed is now the target of the shortcut
373 $this_file_base_dir = "";
374 $file = "";
375 $subfile = $shortcut->Path;
376 }
377 }
378
379 # check for a symlink pointing back to a leading directory
380 if (-d "$dirname/$subfile" && -l "$dirname/$subfile") {
381 # readlink gives a "fatal error" on systems that don't implement
382 # symlinks. This assumes the the -l test above would fail on those.
383 my $linkdest=readlink "$dirname/$subfile";
384 if (!defined ($linkdest)) {
385 # system error - file not found?
386 warn "RecPlug: symlink problem - $!";
387 } else {
388 # see if link points to current or a parent directory
389 if ($linkdest =~ m@^[\./\\]+$@ ||
390 index($dirname, $linkdest) != -1) {
391 warn "RecPlug: Ignoring recursive symlink ($dirname/$subfile -> $linkdest)\n";
392 next;
393 ;
394 }
395 }
396 }
397
398 print $outhandle "RecPlug: preparing metadata for $subfile\n" if ($verbosity > 2);
399
400 # Make a copy of $in_metadata to pass to $subfile
401 $out_metadata = {};
402 &metadatautil::combine_metadata_structures($out_metadata, $in_metadata);
403
404 ## encode the filename as perl5 doesn't handle unicode filenames
405 my $tmpfile = Encode::encode_utf8($subfile);
406
407 # Next add metadata read in XML files (if it is supplied)
408 if ($additionalmetadata == 1) {
409
410 my ($filespec, $mdref);
411 foreach $filespec (@extrametakeys) {
412 ## use the utf8 encoded filename to do the filename comparison
413 if ($tmpfile =~ /^$filespec$/) {
414 print $outhandle "File \"$subfile\" matches filespec \"$filespec\"\n"
415 if ($verbosity > 2);
416 $mdref = $extrametadata{$filespec};
417 &metadatautil::combine_metadata_structures($out_metadata, $mdref);
418 }
419 }
420 }
421
422
423 my $file_subfile = &util::filename_cat($file, $subfile);
424 my $filename_subfile
425 = &util::filename_cat($this_file_base_dir,$file_subfile);
426 if (defined $self->{'inf_timestamp'}) {
427 my $inf_timestamp = $self->{'inf_timestamp'};
428
429 if (! -d $filename_subfile) {
430 my $filename_timestamp = -M $filename_subfile;
431 if ($filename_timestamp > $inf_timestamp) {
432 # filename has been around for longer than inf
433##### print $outhandle "**** Skipping $subfile\n";
434 next;
435 }
436 }
437 }
438
439 # Recursively read each $subfile
440 print $outhandle "RecPlug recurring: $subfile\n" if ($verbosity > 2);
441
442 $count += &plugin::read ($pluginfo, $this_file_base_dir,
443 $file_subfile,
444 $out_metadata, $processor, $maxdocs, ($total_count + $count), $gli);
445 }
446
447 return $count;
448}
449
4501;
Note: See TracBrowser for help on using the repository browser.