root/main/trunk/greenstone2/perllib/plugins/DirectoryPlugin.pm @ 21285

Revision 21285, 20.5 KB (checked in by kjdon, 10 years ago)

added empty removeold method

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