source: gsdl/trunk/perllib/plugins/DirectoryPlugin.pm@ 19811

Last change on this file since 19811 was 19623, checked in by ak19, 15 years ago

when removing RE syntax, need to change double backslash back to single one

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 20.5 KB
Line 
1###########################################################################
2#
3# DirectoryPlugin.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# DirectoryPlugin is a plugin which recurses through directories processing
27# each file it finds - which basically means passing it down the plugin
28# pipeline
29
30package DirectoryPlugin;
31
32use PrintInfo;
33use plugin;
34use util;
35use metadatautil;
36
37use File::Basename;
38use strict;
39no strict 'refs';
40no strict 'subs';
41
42use Encode;
43
44BEGIN {
45 @DirectoryPlugin::ISA = ('PrintInfo');
46}
47
48my $arguments =
49 [ { 'name' => "block_exp",
50 'desc' => "{BasePlugin.block_exp}",
51 'type' => "regexp",
52 'deft' => &get_default_block_exp(),
53 'reqd' => "no" },
54 # this option has been deprecated. leave it here for now so we can warn people not to use it
55 { 'name' => "use_metadata_files",
56 'desc' => "{DirectoryPlugin.use_metadata_files}",
57 'type' => "flag",
58 'reqd' => "no",
59 'hiddengli' => "yes" },
60 { 'name' => "recheck_directories",
61 'desc' => "{DirectoryPlugin.recheck_directories}",
62 'type' => "flag",
63 'reqd' => "no" } ];
64
65my $options = { 'name' => "DirectoryPlugin",
66 'desc' => "{DirectoryPlugin.desc}",
67 'abstract' => "no",
68 'inherits' => "yes",
69 'args' => $arguments };
70
71sub new {
72 my ($class) = shift (@_);
73 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
74 push(@$pluginlist, $class);
75
76 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
77 push(@{$hashArgOptLists->{"OptList"}},$options);
78
79 my $self = new PrintInfo($pluginlist, $inputargs, $hashArgOptLists);
80
81 if ($self->{'info_only'}) {
82 # don't worry about any options or initialisations etc
83 return bless $self, $class;
84 }
85
86 # we have left this option in so we can warn people who are still using it
87 if ($self->{'use_metadata_files'}) {
88 die "ERROR: DirectoryPlugin -use_metadata_files option has been deprecated. Please remove the option and add MetadataXMLPlug to your plugin list instead!\n";
89 }
90
91 $self->{'num_processed'} = 0;
92 $self->{'num_not_processed'} = 0;
93 $self->{'num_blocked'} = 0;
94 $self->{'num_archives'} = 0;
95
96 $self->{'subdir_extrametakeys'} = {};
97
98 return bless $self, $class;
99}
100
101# called once, at the start of processing
102sub init {
103 my $self = shift (@_);
104 my ($verbosity, $outhandle, $failhandle) = @_;
105
106 # verbosity is passed through from the processor
107 $self->{'verbosity'} = $verbosity;
108
109 # as are the outhandle and failhandle
110 $self->{'outhandle'} = $outhandle if defined $outhandle;
111 $self->{'failhandle'} = $failhandle;
112
113}
114
115# called once, after all passes have finished
116sub deinit {
117 my ($self) = @_;
118
119}
120
121# called at the beginning of each plugin pass (import has one, building has many)
122sub begin {
123 my $self = shift (@_);
124 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
125
126 my $proc_package_name = ref $processor;
127
128 if ($proc_package_name !~ /buildproc$/ && $self->{'incremental'} == 1) {
129
130 # Only lookup timestamp info for import.pl, and only if incremental is set
131
132 my $output_dir = $processor->getoutputdir();
133## my $archives_inf = &util::filename_cat($output_dir,"archives.inf");
134 my $doc_db = "archiveinf-doc.gdb";
135 my $archives_inf = &util::filename_cat($output_dir,$doc_db);
136
137 if ( -e $archives_inf ) {
138 $self->{'inf_timestamp'} = -M $archives_inf;
139 }
140 }
141}
142
143# called at the end of each plugin pass
144sub end {
145 my ($self) = shift (@_);
146
147}
148
149
150# called if we are doing incremental building
151sub set_incremental {
152 my $self = shift(@_);
153 my ($incremental) = @_;
154
155 $self->{'incremental'} = $incremental;
156}
157
158# return 1 if this class might recurse using $pluginfo
159sub is_recursive {
160 my $self = shift (@_);
161
162 return 1;
163}
164
165sub get_default_block_exp {
166 my $self = shift (@_);
167
168 return '(?i)(CVS|\.svn|Thumbs\.db|OIDcount|~)$';
169}
170
171sub check_directory_path {
172
173 my $self = shift(@_);
174 my ($dirname) = @_;
175
176 return undef unless (-d $dirname);
177
178 return 0 if ($self->{'block_exp'} ne "" && $dirname =~ /$self->{'block_exp'}/);
179
180 my $outhandle = $self->{'outhandle'};
181
182 # check to make sure we're not reading the archives or index directory
183 my $gsdlhome = quotemeta($ENV{'GSDLHOME'});
184 if ($dirname =~ m/^$gsdlhome\/.*?\/import.*?\/(archives|index)$/) {
185 print $outhandle "DirectoryPlugin: $dirname appears to be a reference to a Greenstone collection, skipping.\n";
186 return 0;
187 }
188
189 # check to see we haven't got a cyclic path...
190 if ($dirname =~ m%(/.*){,41}%) {
191 print $outhandle "DirectoryPlugin: $dirname is 40 directories deep, is this a recursive path? if not increase constant in DirectoryPlugin.pm.\n";
192 return 0;
193 }
194
195 # check to see we haven't got a cyclic path...
196 if ($dirname =~ m%.*?import/(.+?)/import/\1.*%) {
197 print $outhandle "DirectoryPlugin: $dirname appears to be in a recursive loop...\n";
198 return 0;
199 }
200
201 return 1;
202}
203
204# this may be called more than once
205sub sort_out_associated_files {
206
207 my $self = shift (@_);
208 my ($block_hash) = @_;
209 if (!scalar (keys %{$block_hash->{'shared_fileroot'}})) {
210 return;
211 }
212
213 $self->{'assocfile_info'} = {} unless defined $self->{'assocfile_info'};
214 my $metadata = $self->{'assocfile_info'};
215 foreach my $prefix (keys %{$block_hash->{'shared_fileroot'}}) {
216 my $record = $block_hash->{'shared_fileroot'}->{$prefix};
217
218 my $tie_to = $record->{'tie_to'};
219 my $exts = $record->{'exts'};
220
221 if ((defined $tie_to) && (scalar (keys %$exts) > 0)) {
222 # set up fileblocks and assocfile_tobe
223 my $base_file = "$prefix$tie_to";
224 $metadata->{$base_file} = {} unless defined $metadata->{$base_file};
225 my $base_file_metadata = $metadata->{$base_file};
226
227 $base_file_metadata->{'gsdlassocfile_tobe'} = [] unless defined $base_file_metadata->{'gsdlassocfile_tobe'};
228 my $assoc_tobe = $base_file_metadata->{'gsdlassocfile_tobe'};
229 foreach my $e (keys %$exts) {
230 # block the file
231 $block_hash->{'file_blocks'}->{"$prefix$e"} = 1;
232 # set up as an associatd file
233 print STDERR " $self->{'plugin_type'}: Associating $prefix$e with $tie_to version\n";
234 my $mime_type = ""; # let system auto detect this
235 push(@$assoc_tobe,"$prefix$e:$mime_type:");
236
237 }
238 }
239 } # foreach record
240
241 $block_hash->{'shared_fileroot'} = undef;
242 $block_hash->{'shared_fileroot'} = {};
243
244}
245
246
247# do block exp OR special blocking ???
248
249sub file_is_blocked {
250 my $self = shift (@_);
251 my ($block_hash, $filename_full_path) = @_;
252
253 if (defined $block_hash->{'file_blocks'}->{$filename_full_path}) {
254 $self->{'num_blocked'} ++;
255 return 1;
256 }
257 # check Directory plugin's own block_exp
258 if ($self->{'block_exp'} ne "" && $filename_full_path =~ /$self->{'block_exp'}/) {
259 $self->{'num_blocked'} ++;
260 return 1; # blocked
261 }
262 return 0;
263}
264
265
266
267sub file_block_read {
268 my $self = shift (@_);
269 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $gli) = @_;
270
271 my $outhandle = $self->{'outhandle'};
272 my $verbosity = $self->{'verbosity'};
273
274 # Calculate the directory name and ensure it is a directory and
275 # that it is not explicitly blocked.
276 my $dirname = $file;
277 $dirname = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
278
279 my $directory_ok = $self->check_directory_path($dirname);
280 return $directory_ok unless (defined $directory_ok && $directory_ok == 1);
281
282 print $outhandle "Global file scan checking directory: $dirname\n";
283
284 $block_hash->{'all_files'} = {} unless defined $block_hash->{'all_files'};
285
286 $block_hash->{'file_blocks'} = {} unless defined $block_hash->{'file_blocks'};
287 $block_hash->{'shared_fileroot'} = {} unless defined $block_hash->{'shared_fileroot'};
288
289 # Recur over directory contents.
290 my (@dir, $subfile);
291 #my $count = 0;
292
293 print $outhandle "DirectoryPlugin block: getting directory $dirname\n" if ($verbosity > 2);
294
295 # find all the files in the directory
296 if (!opendir (DIR, $dirname)) {
297 if ($gli) {
298 print STDERR "<ProcessingError n='$file' r='Could not read directory $dirname'>\n";
299 }
300 print $outhandle "DirectoryPlugin: WARNING - couldn't read directory $dirname\n";
301 return -1; # error in processing
302 }
303 @dir = readdir (DIR);
304 closedir (DIR);
305
306 for (my $i = 0; $i < scalar(@dir); $i++) {
307 my $subfile = $dir[$i];
308 my $this_file_base_dir = $base_dir;
309 next if ($subfile =~ m/^\.\.?$/);
310
311 # Recursively read each $subfile
312 print $outhandle "DirectoryPlugin block recurring: $subfile\n" if ($verbosity > 2);
313
314 #$count += &plugin::file_block_read ($pluginfo, $this_file_base_dir,
315 &plugin::file_block_read ($pluginfo, $this_file_base_dir,
316 &util::filename_cat($file, $subfile),
317 $block_hash, $metadata, $gli);
318
319 }
320 $self->sort_out_associated_files($block_hash);
321 #return $count;
322
323}
324
325# We don't do metadata_read
326sub metadata_read {
327 my $self = shift (@_);
328 my ($pluginfo, $base_dir, $file, $block_hash,
329 $extrametakeys, $extrametadata, $extrametafile,
330 $processor, $maxdocs, $gli) = @_;
331
332 return undef;
333}
334
335
336# return number of files processed, undef if can't process
337# Note that $base_dir might be "" and that $file might
338# include directories
339
340# This function passes around metadata hash structures. Metadata hash
341# structures are hashes that map from a (scalar) key (the metadata element
342# name) to either a scalar metadata value or a reference to an array of
343# such values.
344
345sub read {
346 my $self = shift (@_);
347 my ($pluginfo, $base_dir, $file, $block_hash, $in_metadata, $processor, $maxdocs, $total_count, $gli) = @_;
348
349 my $outhandle = $self->{'outhandle'};
350 my $verbosity = $self->{'verbosity'};
351
352 # Calculate the directory name and ensure it is a directory and
353 # that it is not explicitly blocked.
354 my $dirname;
355 if ($file eq "") {
356 $dirname = $base_dir;
357 } else {
358 $dirname = $file;
359 $dirname = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
360 }
361
362 my $directory_ok = $self->check_directory_path($dirname);
363 return $directory_ok unless (defined $directory_ok && $directory_ok == 1);
364
365 if (($verbosity > 2) && ((scalar keys %$in_metadata) > 0)) {
366 print $outhandle "DirectoryPlugin: metadata passed in: ",
367 join(", ", keys %$in_metadata), "\n";
368 }
369
370
371 # Recur over directory contents.
372 my (@dir, $subfile);
373 my $count = 0;
374
375 print $outhandle "DirectoryPlugin read: getting directory $dirname\n" if ($verbosity > 2);
376
377 # find all the files in the directory
378 if (!opendir (DIR, $dirname)) {
379 if ($gli) {
380 print STDERR "<ProcessingError n='$file' r='Could not read directory $dirname'>\n";
381 }
382 print $outhandle "DirectoryPlugin: WARNING - couldn't read directory $dirname\n";
383 return -1; # error in processing
384 }
385 @dir = readdir (DIR);
386 closedir (DIR);
387
388 # Re-order the files in the list so any directories ending with .all are moved to the end
389 for (my $i = scalar(@dir) - 1; $i >= 0; $i--) {
390 if (-d &util::filename_cat($dirname, $dir[$i]) && $dir[$i] =~ /\.all$/) {
391 push(@dir, splice(@dir, $i, 1));
392 }
393 }
394
395 # setup the metadata structures. we do a metadata_read pass to see if there is any additional metadata, then pass it to read
396
397 my $additionalmetadata = 0; # is there extra metadata available?
398 my %extrametadata; # maps from filespec to extra metadata keys
399 my %extrametafile; # maps from filespec to the metadata.xml (or similar) file it came from
400 my @extrametakeys; # keys of %extrametadata in order read
401
402
403 my $os_dirsep = &util::get_os_dirsep();
404 my $dirsep = &util::get_dirsep();
405 my $base_dir_regexp = $base_dir;
406 $base_dir_regexp =~ s/\//$os_dirsep/g;
407 my $local_dirname = $dirname;
408 $local_dirname =~ s/^$base_dir_regexp($os_dirsep)//;
409 $local_dirname .= $dirsep;
410
411 if (defined $self->{'subdir_extrametakeys'}->{$local_dirname}) {
412 my $extrakeys = $self->{'subdir_extrametakeys'}->{$local_dirname};
413 foreach my $ek (@$extrakeys) {
414 my $extrakeys_re = $ek->{'re'};
415 my $extrakeys_md = $ek->{'md'};
416 my $extrakeys_mf = $ek->{'mf'};
417 push(@extrametakeys,$extrakeys_re);
418 $extrametadata{$extrakeys_re} = $extrakeys_md;
419 $extrametafile{$extrakeys_re} = $extrakeys_mf;
420 }
421 delete($self->{'subdir_extrametakeys'}->{$local_dirname});
422 }
423
424 # apply metadata pass for each of the files in the directory
425 my $num_files = scalar(@dir);
426 for (my $i = 0; $i < scalar(@dir); $i++) {
427 my $subfile = $dir[$i];
428 my $this_file_base_dir = $base_dir;
429 last if ($maxdocs != -1 && $count >= $maxdocs);
430 next if ($subfile =~ m/^\.\.?$/);
431 my $file_subfile = &util::filename_cat($file, $subfile);
432 my $full_filename = &util::filename_cat($this_file_base_dir, $file_subfile);
433 if ($self->file_is_blocked($block_hash,$full_filename)) {
434 print STDERR "DirectoryPlugin: file $full_filename was blocked for metadata_read\n" if ($verbosity > 2);
435 next;
436 }
437
438 # Recursively read each $subfile
439 print $outhandle "DirectoryPlugin metadata recurring: $subfile\n" if ($verbosity > 2);
440
441 $count += &plugin::metadata_read ($pluginfo, $this_file_base_dir,
442 $file_subfile,$block_hash,
443 \@extrametakeys, \%extrametadata,
444 \%extrametafile,
445 $processor, $maxdocs, $gli);
446 $additionalmetadata = 1;
447 }
448
449 # filter out any extrametakeys that mention subdirectories and store
450 # for later use (i.e. when that sub-directory is being processed)
451
452 foreach my $ek (@extrametakeys) {
453 my ($subdir_re,$extrakey_dir) = &File::Basename::fileparse($ek);
454
455 $extrakey_dir =~ s/\\\./\./g; # remove RE syntax for .
456 $extrakey_dir =~ s/\\\\/\\/g; # remove RE syntax for \
457
458 my $dirsep_re = &util::get_re_dirsep();
459
460 my $ek_non_re = $ek;
461 $ek_non_re =~ s/\\\./\./g; # remove RE syntax for .
462 $ek_non_re =~ s/\\\\/\\/g; # remove RE syntax for \
463 if ($ek_non_re =~ m/$dirsep_re/) { # specifies at least one directory
464 my $md = $extrametadata{$ek};
465 my $mf = $extrametafile{$ek};
466
467 my $subdir_extrametakeys = $self->{'subdir_extrametakeys'};
468
469 my $subdir_rec = { 're' => $subdir_re, 'md' => $md, 'mf' => $mf };
470
471 # when its looked up, it must be relative to the base dir
472 push(@{$subdir_extrametakeys->{"$local_dirname$extrakey_dir"}},$subdir_rec);
473 #push(@{$subdir_extrametakeys->{"$extrakey_dir"}},$subdir_rec);
474 }
475 }
476
477 # import each of the files in the directory
478 $count=0;
479 for (my $i = 0; $i <= scalar(@dir); $i++) {
480 # When every file in the directory has been done, pause for a moment (figuratively!)
481 # If the -recheck_directories argument hasn't been provided, stop now (default)
482 # Otherwise, re-read the contents of the directory to check for new files
483 # Any new files are added to the @dir list and are processed as normal
484 # This is necessary when documents to be indexed are specified in bibliographic DBs
485 # These files are copied/downloaded and stored in a new folder at import time
486 if ($i == $num_files) {
487 last unless $self->{'recheck_directories'};
488
489 # Re-read the files in the directory to see if there are any new files
490 last if (!opendir (DIR, $dirname));
491 my @dirnow = readdir (DIR);
492 closedir (DIR);
493
494 # We're only interested if there are more files than there were before
495 last if (scalar(@dirnow) <= scalar(@dir));
496
497 # Any new files are added to the end of @dir to get processed by the loop
498 my $j;
499 foreach my $subfilenow (@dirnow) {
500 for ($j = 0; $j < $num_files; $j++) {
501 last if ($subfilenow eq $dir[$j]);
502 }
503 if ($j == $num_files) {
504 # New file
505 push(@dir, $subfilenow);
506 }
507 }
508 # When the new files have been processed, check again
509 $num_files = scalar(@dir);
510 }
511
512 my $subfile = $dir[$i];
513 my $this_file_base_dir = $base_dir;
514 last if ($maxdocs != -1 && ($count + $total_count) >= $maxdocs);
515 next if ($subfile =~ /^\.\.?$/);
516
517 my $file_subfile = &util::filename_cat($file, $subfile);
518 my $full_filename
519 = &util::filename_cat($this_file_base_dir,$file_subfile);
520
521 if ($self->file_is_blocked($block_hash,$full_filename)) {
522 print STDERR "DirectoryPlugin: file $full_filename was blocked for read\n" if ($verbosity > 2);
523 next;
524 }
525 #print STDERR "processing $full_filename\n";
526 # Follow Windows shortcuts
527 if ($subfile =~ /(?i)\.lnk$/ && $ENV{'GSDLOS'} =~ /^windows$/i) {
528 require Win32::Shortcut;
529 my $shortcut = new Win32::Shortcut(&util::filename_cat($dirname, $subfile));
530 if ($shortcut) {
531 # The file to be processed is now the target of the shortcut
532 $this_file_base_dir = "";
533 $file = "";
534 $subfile = $shortcut->Path;
535 }
536 }
537
538 # check for a symlink pointing back to a leading directory
539 if (-d "$dirname/$subfile" && -l "$dirname/$subfile") {
540 # readlink gives a "fatal error" on systems that don't implement
541 # symlinks. This assumes the the -l test above would fail on those.
542 my $linkdest=readlink "$dirname/$subfile";
543 if (!defined ($linkdest)) {
544 # system error - file not found?
545 warn "DirectoryPlugin: symlink problem - $!";
546 } else {
547 # see if link points to current or a parent directory
548 if ($linkdest =~ m@^[\./\\]+$@ ||
549 index($dirname, $linkdest) != -1) {
550 warn "DirectoryPlugin: Ignoring recursive symlink ($dirname/$subfile -> $linkdest)\n";
551 next;
552 ;
553 }
554 }
555 }
556
557 print $outhandle "DirectoryPlugin: preparing metadata for $subfile\n" if ($verbosity > 2);
558
559 # Make a copy of $in_metadata to pass to $subfile
560 my $out_metadata = {};
561 &metadatautil::combine_metadata_structures($out_metadata, $in_metadata);
562
563 # check the assocfile_info
564 if (defined $self->{'assocfile_info'}->{$full_filename}) {
565 &metadatautil::combine_metadata_structures($out_metadata, $self->{'assocfile_info'}->{$full_filename});
566 }
567 ## encode the filename as perl5 doesn't handle unicode filenames
568
569 my $tmpfile = Encode::encode_utf8($subfile);
570 #print STDERR "subfile = $subfile, tmpfile = $tmpfile\n";
571 # Next add metadata read in XML files (if it is supplied)
572 if ($additionalmetadata == 1) {
573 foreach my $filespec (@extrametakeys) {
574
575 ## use the utf8 encoded filename to do the filename comparison
576 if ($tmpfile =~ /^$filespec$/) {
577 print $outhandle "File \"$subfile\" matches filespec \"$filespec\"\n"
578 if ($verbosity > 2);
579 my $mdref = $extrametadata{$filespec};
580 my $mfref = $extrametafile{$filespec};
581
582 # Add the list files where the metadata came from
583 # into the metadata table so we can track this
584 # This mechanism is similar to how gsdlassocfile works
585
586 my @metafile_pair = ();
587 foreach my $l (keys %$mfref) {
588 my $f = $mfref->{$l};
589 push (@metafile_pair, "$f : $l");
590 }
591
592 $mdref->{'gsdlmetafile'} = \@metafile_pair;
593
594 &metadatautil::combine_metadata_structures($out_metadata, $mdref);
595 }
596 }
597 }
598
599
600 if (defined $self->{'inf_timestamp'}) {
601 # Look to see if it's a completely new file
602
603 if (!$block_hash->{'new_files'}->{$full_filename}) {
604 # Not a new file, must be an existing file
605 # Let' see if it's newer than the last import.pl
606
607
608 if (! -d $full_filename) {
609 if (!$block_hash->{'reindex_files'}->{$full_filename}) {
610 # filename has been around for longer than inf
611 print $outhandle "**** Skipping $subfile\n" if ($verbosity >3);
612 next;
613 }
614 else {
615 # Remove old folder in archives (might hash to something different)
616 # *** should be doing this on a Del one as well
617 # but leave folder name?? and ensure hashs to
618 # same again??
619
620 # Then let through as new doc??
621
622 # mark to doc-oids that rely on it for re-indexing
623 ## &GDBMUtils::gdbmDatabase();
624 }
625 }
626 }
627 }
628
629 # Recursively read each $subfile
630 print $outhandle "DirectoryPlugin recurring: $subfile\n" if ($verbosity > 2);
631
632 $count += &plugin::read ($pluginfo, $this_file_base_dir,
633 $file_subfile, $block_hash,
634 $out_metadata, $processor, $maxdocs, ($total_count + $count), $gli);
635 }
636
637 return $count;
638}
639
640sub compile_stats {
641 my $self = shift(@_);
642 my ($stats) = @_;
643}
644
6451;
Note: See TracBrowser for help on using the repository browser.