root/main/trunk/greenstone2/perllib/plugouts/BasePlugout.pm @ 32555

Revision 32555, 38.7 KB (checked in by ak19, 21 months ago)

1. In GreenstoneSQLPlugout, removeold is now paramterised (as are keepold, incremental, incremental_mode). 2. Deletion on incremental_build works. But there are more questions. Why are there 4 passes? What to do on reindexing and when to do it (should it happen during GS SQL plugout or plugin)?

  • Property svn:keywords set to Author Date Id Revision
Line 
1###########################################################################
2#
3# BasePlugout.pm -- base class for all the plugout modules
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) 2006 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
26package BasePlugout;
27
28eval {require bytes};
29
30use strict;
31no strict 'subs';
32no strict 'refs';
33
34use dbutil;
35use gsprintf 'gsprintf';
36use printusage;
37use parse2;
38use util;
39use FileUtils;
40use sorttools;
41
42# suppress the annoying "subroutine redefined" warning that various
43# gets cause under perl 5.6
44$SIG{__WARN__} = sub {warn($_[0]) unless ($_[0] =~ /Subroutine\s+\S+\sredefined/)};
45
46my $arguments = [
47        { 'name' => "site_name",
48      'desc' => "{BasPlugout.site_name}",
49      'type' => "string",
50      'reqd' => "no",
51      'hiddengli' => "yes" },
52       { 'name' => "xslt_file",
53    'desc' => "{BasPlugout.xslt_file}",
54    'type' => "string",
55    'reqd' => "no",
56     'deft' => "",
57    'hiddengli' => "no"},
58       { 'name' => "subdir_split_length",
59     'desc' => "{BasPlugout.subdir_split_length}",
60     'type' => "int",
61     'reqd' => "no",
62         'deft' => "8",
63     'hiddengli' => "no"},
64       { 'name' => "subdir_hash_prefix",
65     'desc' => "{BasPlugout.subdir_hash_prefix}",
66     'type' => "flag",
67     'reqd' => "no",
68         'deft' => "0",
69     'hiddengli' => "no"},
70       { 'name' => "gzip_output",
71    'desc' => "{BasPlugout.gzip_output}",
72    'type' => "flag",
73    'reqd' => "no", 
74        'hiddengli' => "no"},
75        { 'name' => "verbosity",
76    'desc' => "{BasPlugout.verbosity}",
77    'type' => "int",
78        'deft' =>  "0",
79    'reqd' => "no", 
80        'hiddengli' => "no"},
81      { 'name' => "output_info",
82    'desc' => "{BasPlugout.output_info}",
83    'type' => "string",   
84    'reqd' => "yes",
85    'hiddengli' => "yes"},       
86       { 'name' => "output_handle",
87    'desc' => "{BasPlugout.output_handle}",
88    'type' => "string",
89        'deft' =>  'STDERR',
90    'reqd' => "no",
91    'hiddengli' => "yes"},
92       { 'name' => "debug",
93     'desc' => "{BasPlugout.debug}",
94     'type' => "flag",
95     'reqd' => "no",
96     'hiddengli' => "yes"},
97       { 'name' => 'no_rss',
98         'desc' => "{BasPlugout.no_rss}",
99         'type' => 'flag',
100         'reqd' => 'no',
101         'hiddengli' => 'yes'},
102       { 'name' => 'rss_title',
103         'desc' => "{BasPlugout.rss_title}",
104         'type' => 'string',
105     'deft' => 'dc.Title',
106         'reqd' => 'no',
107         'hiddengli' => 'yes'},
108    { 'name' => "no_auxiliary_databases",
109      'desc' => "{BasPlugout.no_auxiliary_databases}",
110      'type' => "flag",
111      'reqd' => "no",
112      'hiddengli' => "yes"}
113
114];
115
116my $options = { 'name'     => "BasePlugout",
117        'desc'     => "{BasPlugout.desc}",
118        'abstract' => "yes",
119        'inherits' => "no",
120        'args'     => $arguments};
121
122sub new
123{
124    my $class = shift (@_);
125
126    my ($plugoutlist,$args,$hashArgOptLists) = @_;
127    push(@$plugoutlist, $class);
128
129    my $plugout_name = (defined $plugoutlist->[0]) ? $plugoutlist->[0] : $class;
130
131    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
132    push(@{$hashArgOptLists->{"OptList"}},$options);
133
134    my $self = {};
135    $self->{'plugout_type'} = $class;
136    $self->{'option_list'} = $hashArgOptLists->{"OptList"};
137    $self->{"info_only"} = 0;
138
139    # Check if gsdlinfo is in the argument list or not - if it is, don't parse
140    # the args, just return the object.
141    #print STDERR "#### " . join(",", @${args}) . "\n\n";
142    my $v=0;
143    foreach my $strArg (@{$args})
144    {
145    if(defined $strArg) {
146        if($strArg eq "-gsdlinfo")
147        {
148        $self->{"info_only"} = 1;
149        return bless $self, $class;
150        }       
151        elsif ($strArg eq "-site_name") {
152        $v = $strArg;
153        }
154        elsif($v eq "-site_name") {
155        $self->{'site_name'} = $strArg;
156        }
157    }
158    }
159   
160    delete $self->{"info_only"};
161   
162    if(parse2::parse($args,$hashArgOptLists->{"ArgList"},$self) == -1)
163    {
164    my $classTempClass = bless $self, $class;
165    print STDERR "<BadPlugout d=$plugout_name>\n";
166    &gsprintf(STDERR, "\n{BasPlugout.bad_general_option}\n", $plugout_name);
167    $classTempClass->print_txt_usage("");  # Use default resource bundle
168    die "\n";
169    }
170
171 
172    if(defined $self->{'xslt_file'} &&  $self->{'xslt_file'} ne "")
173    {
174    my $full_file_path = &util::locate_config_file($self->{'xslt_file'});
175    if (!defined $full_file_path) {
176        print STDERR "Can not find $self->{'xslt_file'}, please make sure you have supplied the correct file path or put the file into the collection's etc or greenstone's etc folder\n";
177        die "\n";
178    }
179    $self->{'xslt_file'} = $full_file_path;
180    }
181
182    # for group processing
183    $self->{'gs_count'} = 0;
184    $self->{'group_position'} = 1;
185
186    $self->{'keep_import_structure'} = 0;
187
188    $self->{'generate_databases'} = 1;
189    if ($self->{'no_auxiliary_databases'}) {
190    $self->{'generate_databases'} = 0;
191    }
192    undef $self->{'no_auxiliary_databases'};
193    return bless $self, $class;
194
195}
196
197# implement this in subclass if you want to do some initialization after
198# loading and setting parameters, and before processing the documents.
199sub begin {
200
201    my $self= shift (@_);
202
203}
204# implement in subclasses if it needs some non-group related cleanup (post-group cleanup
205# Like begin(), end() is also called by inexport.pm
206sub end {
207    my $self= shift (@_);
208
209}
210sub print_xml_usage
211{
212    my $self = shift(@_);
213    my $header = shift(@_);
214    my $high_level_information_only = shift(@_);
215
216    # XML output is always in UTF-8
217    gsprintf::output_strings_in_UTF8;
218
219    if ($header) {
220    &PrintUsage::print_xml_header("plugout");
221    }
222    $self->print_xml($high_level_information_only);
223}
224
225
226sub print_xml
227{
228    my $self = shift(@_);
229    my $high_level_information_only = shift(@_);
230
231    my $optionlistref = $self->{'option_list'};
232    my @optionlist = @$optionlistref;
233    my $plugoutoptions = shift(@$optionlistref);
234    return if (!defined($plugoutoptions));
235
236    gsprintf(STDERR, "<PlugoutInfo>\n");
237    gsprintf(STDERR, "  <Name>$plugoutoptions->{'name'}</Name>\n");
238    my $desc = gsprintf::lookup_string($plugoutoptions->{'desc'});
239    $desc =~ s/</&amp;lt;/g; # doubly escaped
240    $desc =~ s/>/&amp;gt;/g;
241    gsprintf(STDERR, "  <Desc>$desc</Desc>\n");
242    gsprintf(STDERR, "  <Abstract>$plugoutoptions->{'abstract'}</Abstract>\n");
243    gsprintf(STDERR, "  <Inherits>$plugoutoptions->{'inherits'}</Inherits>\n");
244    unless (defined($high_level_information_only)) {
245    gsprintf(STDERR, "  <Arguments>\n");
246    if (defined($plugoutoptions->{'args'})) {
247        &PrintUsage::print_options_xml($plugoutoptions->{'args'});
248    }
249    gsprintf(STDERR, "  </Arguments>\n");
250
251    # Recurse up the plugout hierarchy
252    $self->print_xml();
253    }
254    gsprintf(STDERR, "</PlugoutInfo>\n");
255}
256
257
258sub print_txt_usage
259{
260    my $self = shift(@_);
261
262    # Print the usage message for a plugout (recursively)
263    my $descoffset = $self->determine_description_offset(0);
264    $self->print_plugout_usage($descoffset, 1);
265}
266
267sub determine_description_offset
268{
269    my $self = shift(@_);
270    my $maxoffset = shift(@_);
271
272    my $optionlistref = $self->{'option_list'};
273    my @optionlist = @$optionlistref;
274    my $plugoutoptions = pop(@$optionlistref);
275    return $maxoffset if (!defined($plugoutoptions));
276
277    # Find the length of the longest option string of this download
278    my $plugoutargs = $plugoutoptions->{'args'};
279    if (defined($plugoutargs)) {
280    my $longest = &PrintUsage::find_longest_option_string($plugoutargs);
281    if ($longest > $maxoffset) {
282        $maxoffset = $longest;
283    }
284    }
285
286    # Recurse up the download hierarchy
287    $maxoffset = $self->determine_description_offset($maxoffset);
288    $self->{'option_list'} = \@optionlist;
289    return $maxoffset;
290}
291
292
293sub print_plugout_usage
294{
295    my $self = shift(@_);
296    my $descoffset = shift(@_);
297    my $isleafclass = shift(@_);
298
299    my $optionlistref = $self->{'option_list'};
300    my @optionlist = @$optionlistref;
301    my $plugoutoptions = shift(@$optionlistref);
302    return if (!defined($plugoutoptions));
303
304    my $plugoutname = $plugoutoptions->{'name'};
305    my $plugoutargs = $plugoutoptions->{'args'};
306    my $plugoutdesc = $plugoutoptions->{'desc'};
307
308    # Produce the usage information using the data structure above
309    if ($isleafclass) {
310    if (defined($plugoutdesc)) {
311        gsprintf(STDERR, "$plugoutdesc\n\n");
312    }
313    gsprintf(STDERR, " {common.usage}: plugout $plugoutname [{common.options}]\n\n");
314    }
315
316    # Display the download options, if there are some
317    if (defined($plugoutargs)) {
318    # Calculate the column offset of the option descriptions
319    my $optiondescoffset = $descoffset + 2;  # 2 spaces between options & descriptions
320
321    if ($isleafclass) {
322        gsprintf(STDERR, " {common.specific_options}:\n");
323    }
324    else {
325        gsprintf(STDERR, " {common.general_options}:\n", $plugoutname);
326    }
327
328    # Display the download options
329    &PrintUsage::print_options_txt($plugoutargs, $optiondescoffset);
330    }
331
332    # Recurse up the download hierarchy
333    $self->print_plugout_usage($descoffset, 0);
334    $self->{'option_list'} = \@optionlist;
335}
336
337
338sub error
339{
340      my ($strFunctionName,$strError) = @_;
341    {
342    print "Error occoured in BasePlugout.pm\n".
343        "In Function: ".$strFunctionName."\n".
344        "Error Message: ".$strError."\n";
345    exit(-1);
346    } 
347}
348
349# GreenstoneSQLPlugout needs to know whether we're doing removeold or not
350sub set_incremental_options {
351    my $self= shift (@_);
352    my ($removeold, $keepold, $incremental, $incremental_mode) = @_;
353   
354    $self->{'removeold'}        = $removeold;
355    $self->{'keepold'}          = $keepold;
356    $self->{'incremental'}      = $incremental;
357    $self->{'incremental_mode'} = $incremental_mode;
358}
359
360# OIDtype may be "hash" or "hash_on_full_filename" or "incremental" or "filename" or "dirname" or "full_filename" or "assigned"
361sub set_OIDtype {
362    my $self = shift (@_);
363    my ($type, $metadata) = @_;
364
365    if ($type =~ /^(hash|hash_on_full_filename|incremental|filename|dirname|full_filename|assigned)$/) {
366    $self->{'OIDtype'} = $type;
367    } else {
368    $self->{'OIDtype'} = "hash";
369    }
370    if ($type =~ /^assigned$/) {
371    if (defined $metadata) {
372        $self->{'OIDmetadata'} = $metadata;
373    } else {
374        $self->{'OIDmetadata'} = "dc.Identifier";
375    }
376    }
377}
378
379sub set_output_dir
380{
381    my $self = shift @_;
382    my ($output_dir) = @_;
383
384   $self->{'output_dir'} = $output_dir;
385}
386
387sub setoutputdir
388{
389    my $self = shift @_;
390    my ($output_dir) = @_;
391
392    $self->{'output_dir'} = $output_dir;
393}
394
395sub get_output_dir
396{
397    my $self = shift (@_);
398
399   return $self->{'output_dir'};
400}
401
402sub getoutputdir
403{
404    my $self = shift (@_);
405
406    return $self->{'output_dir'};
407}
408
409sub getoutputinfo
410{
411    my $self = shift (@_);
412
413    return $self->{'output_info'};
414}
415
416
417sub get_output_handler
418{
419    my $self = shift (@_);
420
421    my ($output_file_name) = @_;
422
423    my $fh;
424    &FileUtils::openFileHandle($output_file_name, '>', \$fh) or die('Can not open a file handler for: ' . $output_file_name . "\n");
425
426    return $fh;
427}
428
429sub release_output_handler
430{
431    my $self = shift (@_);
432    my ($outhandler) = @_;
433
434    close($outhandler);
435
436}
437
438sub output_xml_header {
439    my $self = shift (@_);
440    my ($handle,$docroot,$nondoctype) = @_;
441   
442   
443    #print $handle '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . "\n";
444   
445    #For Dspace must be UTF in lower case
446    print $handle '<?xml version="1.0" encoding="utf-8" standalone="no"?>' . "\n";
447   
448    if (!defined $nondoctype){
449    my $doctype = (defined $docroot) ? $docroot : "Section";
450
451    # Used to be '<!DOCTYPE Archive SYSTEM ...'
452   
453    print $handle "<!DOCTYPE $doctype SYSTEM \"http://greenstone.org/dtd/Archive/1.0/Archive.dtd\">\n";
454    }
455
456    print $handle "<$docroot>\n" if defined $docroot;
457}
458
459sub output_xml_footer {
460    my $self = shift (@_);
461    my ($handle,$docroot) = @_;
462    print $handle "</$docroot>\n" if defined $docroot;
463}
464
465
466sub output_general_xml_header
467{
468    my $self = shift (@_);
469    my ($handle,$docroot,$opt_attributes,$opt_dtd, $opt_doctype) = @_;
470   
471    print $handle '<?xml version="1.0" encoding="utf-8" standalone="no"?>' . "\n";
472   
473    if (defined $opt_dtd) {
474        my $doctype = (defined $opt_doctype) ? $opt_doctype : $docroot;
475    print $handle "<!DOCTYPE $doctype SYSTEM \"$opt_dtd\">\n";
476    }
477
478    if (defined $docroot) {
479        my $full_docroot = $docroot;
480        if (defined $opt_attributes) {
481          $full_docroot .= " $opt_attributes";
482        }
483
484        print $handle "<$full_docroot>\n"
485      }
486}
487
488sub output_general_xml_footer
489{
490    output_xml_footer(@_);
491}
492
493# This is called by the plugins after read_into_doc_obj generates the doc_obj.
494sub process {
495    my $self = shift (@_);
496    my ($doc_obj) = @_;
497
498    my $output_info = $self->{'output_info'};
499    return if (!defined $output_info);
500
501    # for OAI purposes
502    $doc_obj->set_lastmodified();
503    $doc_obj->set_oailastmodified();
504
505    # find out which directory to save to
506    my $doc_dir = "";
507    if ($self->is_group()) {
508    $doc_dir = $self->get_group_doc_dir($doc_obj);     
509    } else {
510    $doc_dir = $self->get_doc_dir($doc_obj);
511    }
512     
513    ##############################
514    # call subclass' saveas method
515    ##############################
516    $self->saveas($doc_obj,$doc_dir);
517
518    # write out data to archiveinf-doc.db
519    if ($self->{'generate_databases'}) {
520    $self->archiveinf_db($doc_obj);
521    }
522    if ($self->is_group()) {
523    $self->{'gs_count'}++; # do we want this for all cases?
524    $self->{'group_position'}++;
525    }
526}
527
528sub store_output_info_reference {
529    my $self = shift (@_);
530    my ($doc_obj) = @_;
531
532    my $output_info = $self->{'output_info'};
533    my $metaname = $self->{'sortmeta'};
534
535    my $group_position;
536    if ($self->is_group()) {
537    $group_position = $self->{'group_position'};
538    }
539    if (!defined $metaname || $metaname !~ /\S/) {
540    my $OID = $doc_obj->get_OID();
541    $output_info->add_info($OID,$self->{'short_doc_file'}, undef, "", $group_position);
542    return;
543    }
544   
545    if ($metaname eq "OID") { # sort by OID
546    my $OID = $doc_obj->get_OID();
547    $output_info->add_info($OID,$self->{'short_doc_file'}, undef, $OID, undef);
548    return;
549    }
550   
551    my $metadata = "";
552    my $top_section = $doc_obj->get_top_section();
553   
554    my @commameta_list = split(/,/, $metaname);
555    foreach my $cmn (@commameta_list) {
556    my $meta = $doc_obj->get_metadata_element($top_section, $cmn);
557    if ($meta) {
558        # do remove prefix/suffix - this will apply to all values
559        $meta =~ s/^$self->{'removeprefix'}// if defined $self->{'removeprefix'};         
560        $meta =~ s/$self->{'removesuffix'}$// if defined $self->{'removesuffix'};
561        $meta = &sorttools::format_metadata_for_sorting($cmn, $meta, $doc_obj);
562        $metadata .= $meta if ($meta);
563    }
564    }
565
566    # store reference in the output_info     
567    $output_info->add_info($doc_obj->get_OID(),$self->{'short_doc_file'}, undef, $metadata,undef);
568   
569}
570
571
572
573sub saveas {
574    my $self = shift (@_);
575    my ($doc_obj, $doc_dir) = @_;
576   
577    die "Basplug::saveas function must be implemented in sub classes\n";
578}
579
580sub get_group_doc_dir {
581    my $self = shift (@_);
582    my ($doc_obj) = @_;
583
584    my $outhandle = $self->{'output_handle'};
585    my $OID = $doc_obj->get_OID();
586    $OID = "NULL" unless defined $OID;
587
588    my $groupsize = $self->{'group_size'};
589    my $gs_count = $self->{'gs_count'};
590    my $open_new_file = (($gs_count % $groupsize)==0);
591
592    my $doc_dir;
593
594    if (!$open_new_file && scalar(@{$doc_obj->get_assoc_files()})>0) {
595    # if we have some assoc files, then we will need to start a new file
596    if ($self->{'verbosity'} > 2) {
597        print $outhandle " Starting a archives folder for $OID as it has associated files\n";
598    }
599    $open_new_file = 1;
600    }
601   
602    # opening a new file
603    if (($open_new_file)  || !defined($self->{'gs_doc_dir'})) {
604    # first we close off the old output
605    if ($gs_count>0)
606    {
607        return if (!$self->close_group_output());
608    }
609
610    # this will create the directory
611    $doc_dir = $self->get_doc_dir ($doc_obj);
612    $self->{'new_doc_dir'} = 1;
613    $self->{'gs_doc_dir'} = $doc_dir;
614    $self->{'group_position'} = 1;
615    }
616    else {
617    $doc_dir = $self->{'gs_doc_dir'};
618    $self->{'new_doc_dir'} = 0;
619    }
620    return $doc_dir;
621
622}
623sub get_doc_dir {
624   
625    my $self = shift (@_);
626    my ($doc_obj) = @_;
627
628    my $OID = $doc_obj->get_OID();
629    $OID = "NULL" unless defined $OID;
630
631    my $working_dir  = $self->get_output_dir();
632    my $working_info = $self->{'output_info'};
633    return if (!defined $working_info);
634
635    my $doc_info = $working_info->get_info($OID);
636    my $doc_dir = '';
637
638    if (defined $doc_info && scalar(@$doc_info) >= 1)
639    {
640    # This OID already has an archives directory, so use it again
641    $doc_dir = $doc_info->[0];
642    $doc_dir =~ s/\/?((doc(mets)?)|(dublin_core))\.xml(\.gz)?$//;
643    }
644    elsif ($self->{'keep_import_structure'})
645    {
646    my $source_filename = $doc_obj->get_source_filename();
647    $source_filename = &File::Basename::dirname($source_filename);
648    $source_filename =~ s/[\\\/]+/\//g;
649    $source_filename =~ s/\/$//;
650
651        $doc_dir = substr($source_filename, length($ENV{'GSDLIMPORTDIR'}) + 1);
652    }
653
654    # We have to use a new archives directory for this document
655    if ($doc_dir eq "")
656    {
657    $doc_dir = $self->get_new_doc_dir ($working_info, $working_dir, $OID);
658    }
659
660    &FileUtils::makeAllDirectories(&FileUtils::filenameConcatenate($working_dir, $doc_dir));
661
662    return $doc_dir;
663}
664
665
666## @function get_new_doc_dir()
667#
668# Once a doc object is ready to write to disk (and hence has a nice OID),
669# generate a unique subdirectory to write the information to.
670#
671# - create the directory as part of this call, to try and avoid race conditions
672#   found in parallel processing [jmt12]
673#
674# @todo figure out what the rule regarding $work_info->size() is meant to do
675#
676# @todo determine what $self->{'group'} is, and whether it should affect
677#       directory creation
678#
679sub get_new_doc_dir
680{
681  my $self = shift (@_);
682  my($working_info,$working_dir,$OID) = @_;
683
684  my $doc_dir = "";
685  my $doc_dir_rest = $OID;
686
687  # remove any \ and / from the OID
688  $doc_dir_rest =~ s/[\\\/]//g;
689
690  # Remove ":" if we are on Windows OS, as otherwise they get confused with the drive letters
691  if ($ENV{'GSDLOS'} =~ /^windows$/i)
692  {
693    $doc_dir_rest =~ s/\://g;
694  }
695
696  # we generally create a unique directory by adding consequtive fragments of
697  # the document identifier (split by some predefined length - defaulting to
698  # 8) until we find a directory that doesn't yet exist. Note that directories
699  # that contain a document have a suffix ".dir" (whereas those that contain
700  # only subdirectories have no suffix).
701  my $doc_dir_num = 0; # how many directories deep we are
702  my $created_directory = 0; # have we successfully created a new directory
703  do
704  {
705    # (does this work on windows? - jmt12)
706    if ($doc_dir_num > 0)
707    {
708      $doc_dir .= '/';
709    }
710
711    # the default matching pattern grabs the next 'subdir_split_length'
712    # characters of the OID to act as the next subdirectory
713    my $pattern = '^(.{1,' . $self->{'subdir_split_length'} . '})';
714
715    # Do we count any "HASH" prefix against the split length limit?
716    if ($self->{'subdir_hash_prefix'} && $doc_dir_num == 0)
717    {
718      $pattern = '^((HASH)?.{1,' . $self->{'subdir_split_length'} . '})';
719    }
720
721    # Note the use of 's' to both capture the next chuck of OID and to remove
722    # it from OID at the same time
723    if ($doc_dir_rest =~ s/$pattern//i)
724    {
725      $doc_dir .= $1;
726      $doc_dir_num++;
727
728      my $full_doc_dir = &FileUtils::filenameConcatenate($working_dir, $doc_dir . '.dir');
729      if(!FileUtils::directoryExists($full_doc_dir))
730      {
731        &FileUtils::makeAllDirectories($full_doc_dir);
732        $created_directory = 1;
733      }
734
735      ###rint STDERR "[DEBUG] BasePlugout::get_new_doc_dir(<working_info>, $working_dir, $oid)\n";
736      ###rint STDERR " - create directory: $full_doc_dir => $created_directory\n";
737      ###rint STDERR " - rest: $doc_dir_rest\n";
738      ###rint STDERR " - working_info->size(): " . $working_info->size() . " [ < 1024 ?]\n";
739      ###rint STDERR " - doc_dir_num: " . $doc_dir_num . "\n";
740    }
741  }
742  while ($doc_dir_rest ne '' && ($created_directory == 0 || ($working_info->size() >= 1024 && $doc_dir_num < 2)));
743
744  # not unique yet? Add on an incremental suffix until we are unique
745  my $i = 1;
746  my $doc_dir_base = $doc_dir;
747  while ($created_directory == 0)
748  {
749    $doc_dir = $doc_dir_base . '-' . $i;
750    $created_directory = &FileUtils::makeAllDirectories(&FileUtils::filenameConcatenate($working_dir, $doc_dir . '.dir'));
751    $i++;
752  }
753
754  # in theory this should never happen
755  if (!$created_directory)
756  {
757    die("Error! Failed to create directory for document: " . $doc_dir_base . "\n");
758  }
759
760  return $doc_dir . '.dir';
761}
762## get_new_doc_dir()
763
764
765sub process_assoc_files {
766    my $self = shift (@_);
767    my ($doc_obj, $doc_dir, $handle) = @_;
768
769    my $outhandle = $self->{'output_handle'};
770   
771    my $output_dir = $self->get_output_dir();
772    return if (!defined $output_dir);
773
774    &FileUtils::makeAllDirectories($output_dir) unless &FileUtils::directoryExists($output_dir);
775     
776    my $working_dir = &FileUtils::filenameConcatenate($output_dir, $doc_dir);
777    &FileUtils::makeAllDirectories($working_dir) unless &FileUtils::directoryExists($working_dir);
778
779    my @assoc_files = ();
780    my $filename;;
781
782    my $source_filename = $doc_obj->get_source_filename();
783
784    my $collect_dir = $ENV{'GSDLCOLLECTDIR'};
785
786    if (defined $collect_dir) {
787    my $dirsep_regexp = &util::get_os_dirsep();
788
789    if ($collect_dir !~ /$dirsep_regexp$/) {
790        $collect_dir .= &util::get_dirsep(); # ensure there is a slash at the end
791    }
792
793    # This test is never going to fail on Windows -- is this a problem?
794     
795    if ($source_filename !~ /^$dirsep_regexp/) {
796        $source_filename = &FileUtils::filenameConcatenate($collect_dir, $source_filename);
797    }
798    }
799
800
801    # set the assocfile path (even if we have no assoc files - need this for lucene)
802    $doc_obj->set_utf8_metadata_element ($doc_obj->get_top_section(),
803                     "assocfilepath",
804                     "$doc_dir");
805    foreach my $assoc_file_rec (@{$doc_obj->get_assoc_files()}) {
806    my ($dir, $afile) = $assoc_file_rec->[1] =~ /^(.*?)([^\/\\]+)$/;
807    $dir = "" unless defined $dir;
808       
809    my $utf8_real_filename = $assoc_file_rec->[0];
810
811    # for some reasons the image associate file has / before the full path
812    $utf8_real_filename =~ s/^\\(.*)/$1/i;
813
814##  my $real_filename = &util::utf8_to_real_filename($utf8_real_filename);
815    my $real_filename = $utf8_real_filename;
816    $real_filename = &util::downgrade_if_dos_filename($real_filename);
817
818    if (&FileUtils::fileExists($real_filename)) {
819
820        $filename = &FileUtils::filenameConcatenate($working_dir, $afile);
821
822            &FileUtils::hardLink($real_filename, $filename, $self->{'verbosity'});
823
824        $doc_obj->add_utf8_metadata ($doc_obj->get_top_section(),
825                     "gsdlassocfile",
826                     "$afile:$assoc_file_rec->[2]:$dir");
827    } elsif ($self->{'verbosity'} > 1) {
828        print $outhandle "BasePlugout::process couldn't copy the associated file " .
829        "$real_filename to $afile\n";
830    }
831    }
832}
833
834
835sub process_metafiles_metadata
836{
837    my $self = shift (@_);
838    my ($doc_obj) = @_;
839
840    my $top_section = $doc_obj->get_top_section();
841    my $metafiles = $doc_obj->get_metadata($top_section,"gsdlmetafile");
842
843    foreach my $metafile_pair (@$metafiles) {
844    my ($full_metafile,$metafile) = split(/ : /,$metafile_pair);
845
846    $doc_obj->metadata_file($full_metafile,$metafile);
847    }
848
849    $doc_obj->delete_metadata($top_section,"gsdlmetafile");
850}
851
852sub archiveinf_files_to_field
853{
854    my $self = shift(@_);
855    my ($files,$field,$collect_dir,$oid_files,$reverse_lookups) = @_;
856
857    foreach my $file_rec (@$files) {
858    my $real_filename = (ref $file_rec eq "ARRAY") ? $file_rec->[0] : $file_rec;
859    my $full_file = (ref $file_rec eq "ARRAY") ? $file_rec->[1] : $file_rec;
860    # for some reasons the image associate file has / before the full path
861    $real_filename =~ s/^\\(.*)/$1/i;
862
863    my $raw_filename = &util::downgrade_if_dos_filename($real_filename);
864
865    if (&FileUtils::fileExists($raw_filename)) {
866
867#       if (defined $collect_dir) {
868#       my $collect_dir_re_safe = $collect_dir;
869#       $collect_dir_re_safe =~ s/\\/\\\\/g; # use &util::filename_to_regex()
870#       $collect_dir_re_safe =~ s/\./\\./g;##
871
872#       $real_filename =~ s/^$collect_dir_re_safe//;
873#       }
874       
875        if (defined $reverse_lookups) {
876        $reverse_lookups->{$real_filename} = 1;
877        }
878
879        if($field =~ m@assoc-file|src-file|meta-file@) {
880        $raw_filename = &util::abspath_to_placeholders($raw_filename);
881        }
882
883###     push(@{$oid_files->{$field}},$full_file);       
884        push(@{$oid_files->{$field}},$raw_filename);
885    }
886    else {
887        print STDERR "Warning: archiveinf_files_to_field()\n  $real_filename does not appear to be on the file system\n";
888    }
889    }
890}
891
892sub archiveinf_db
893{
894    my $self = shift (@_);
895    my ($doc_obj) = @_;
896
897    my $verbosity = $self->{'verbosity'};
898
899    my $collect_dir = $ENV{'GSDLCOLLECTDIR'};
900    if (defined $collect_dir) {
901    my $dirsep_regexp = &util::get_os_dirsep();
902
903    if ($collect_dir !~ /$dirsep_regexp$/) {
904        # ensure there is a slash at the end
905        $collect_dir .= &util::get_dirsep();
906    }
907    }
908
909    my $oid = $doc_obj->get_OID();
910    my $source_filename = $doc_obj->get_unmodified_source_filename();
911    my $working_info = $self->{'output_info'};
912    my $doc_info = $working_info->get_info($oid);
913
914    my ($doc_file,$index_status,$sortmeta, $group_position) = @$doc_info;
915    # doc_file is the path to the archive doc.xml. Make sure it has unix
916    # slashes, then if the collection is copied to linux, it can be built without reimport
917    $doc_file =~ s/\\/\//g;
918    my $oid_files = { 'doc-file' => $doc_file,
919              'index-status' => $index_status,
920              'src-file' => $source_filename,
921              'sort-meta' => $sortmeta,
922              'assoc-file' => [],
923              'meta-file'  => [] };
924    if (defined $group_position) {
925    $oid_files->{'group-position'} = $group_position;
926    }
927    my $reverse_lookups = { $source_filename => "1" };
928
929
930    $self->archiveinf_files_to_field($doc_obj->get_source_assoc_files(),"assoc-file",
931                     $collect_dir,$oid_files,$reverse_lookups);
932
933
934    $self->archiveinf_files_to_field($doc_obj->get_meta_files(),"meta-file",
935                     $collect_dir,$oid_files);
936
937    # Get the infodbtype value for this collection from the arcinfo object
938    my $infodbtype = $self->{'output_info'}->{'infodbtype'};
939    my $output_dir = $self->{'output_dir'};
940
941    my $doc_db = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $output_dir);
942
943    ##print STDERR "*** To set in db: \n\t$doc_db\n\t$oid\n\t$doc_db_text\n";
944
945    if (!$self->{'no_rss'})
946    {
947      if (($oid_files->{'index-status'} eq "I") || ($oid_files->{'index-status'} eq "R")) {
948    my $top_section = $doc_obj->get_top_section();
949   
950    # rss_title can be set in collect.cfg as follows:
951    #      plugout GreenstoneXMLPlugout -rss_title "dc.Title; ex.Title"
952    # rss_title is a semi-colon or comma-separated list of the metadata field names that should
953    # be consulted in order to obtain a Title (anchor text) for the RSS document link.   
954    # If not specified, rss_title will default to dc.Title, and fall back on Untitled
955    my $metafieldnames = $self->{'rss_title'};
956    my @metafieldarray = split(/[,;] ?/,$metafieldnames); # , or ; separator can be followed by an optional space
957    my $titles;
958    #@$titles=(); # at worst @$titles will be (), as get_metadata(dc.Titles) may return ()
959    foreach my $metafieldname (@metafieldarray) {
960        $metafieldname =~ s@^ex\.@@; # if ex.Title, need to get_metadata() on metafieldname=Title
961        $titles = $doc_obj->get_metadata($top_section,$metafieldname);
962
963        if(scalar(@$titles) != 0) { # found at least one title for one metafieldname
964           last; # break out of the loop
965        }
966    }
967   
968    # if ex.Title was listed in the metafieldnames, then we'll surely have a value for title for this doc
969    # otherwise, if we have no titles at this point, add in a default of Untitled as this doc's title
970    if(scalar(@$titles) == 0) { #&& $metafieldnames !~ m@ex.Title@) {
971        push(@$titles, "Untitled");
972    }
973   
974    # encode basic html entities like <>"& in the title(s), since the & char can break RSS links
975    for (my $i = 0; $i < scalar(@$titles); $i++) {
976        &ghtml::htmlsafe(@$titles[$i]);
977    }
978
979    my $dc_title = join("; ", @$titles);
980
981    if ($oid_files->{'index-status'} eq "R") {
982        $dc_title .= " (Updated)";
983    }
984
985        my $rss_entry = "<item>\n";
986        $rss_entry   .= "   <title>$dc_title</title>\n";
987    if(&util::is_gs3()) {
988        $rss_entry   .= "   <link>_httpdomain__httpcollection_/document/$oid</link>\n";
989    } else {
990        $rss_entry   .= "   <link>_httpdomainHtmlsafe__httpcollection_/document/$oid</link>\n";
991    }
992    $rss_entry   .= "</item>";
993
994        if (defined(&dbutil::supportsRSS) && &dbutil::supportsRSS($infodbtype))
995        {
996          my $rss_db = &dbutil::get_infodb_file_path($infodbtype, 'rss-items', $output_dir);
997          my $rss_db_fh = &dbutil::open_infodb_write_handle($infodbtype, $rss_db, 'append');
998          &dbutil::write_infodb_rawentry($infodbtype, $rss_db_fh, $oid, $rss_entry);
999          &dbutil::close_infodb_write_handle($infodbtype, $rss_db_fh);
1000        }
1001        else
1002        {
1003          my $rss_filename = &FileUtils::filenameConcatenate($output_dir,"rss-items.rdf");
1004          my $rss_fh;
1005          if (&FileUtils::openFileHandle($rss_filename, '>>', \$rss_fh, "utf8"))
1006          {
1007        print $rss_fh $rss_entry . "\n";
1008        &FileUtils::closeFileHandle($rss_filename, \$rss_fh);
1009          }
1010          else
1011          {
1012        print STDERR "**** Failed to open $rss_filename\n$!\n";
1013          }
1014        }
1015      }
1016    }
1017
1018    $oid_files->{'doc-file'} = [ $oid_files->{'doc-file'} ];
1019    $oid_files->{'index-status'} = [ $oid_files->{'index-status'} ];
1020    $oid_files->{'src-file'} = &util::abspath_to_placeholders($oid_files->{'src-file'});
1021    $oid_files->{'src-file'} = [ $oid_files->{'src-file'} ];
1022    $oid_files->{'sort-meta'} = [ $oid_files->{'sort-meta'} ];
1023    if (defined $oid_files->{'group-position'}) {
1024    $oid_files->{'group-position'} = [ $oid_files->{'group-position'} ];
1025    }
1026
1027    my $infodb_file_handle = &dbutil::open_infodb_write_handle($infodbtype, $doc_db, "append");
1028    &dbutil::write_infodb_entry($infodbtype, $infodb_file_handle, $oid, $oid_files);
1029    &dbutil::close_infodb_write_handle($infodbtype, $infodb_file_handle);
1030
1031    foreach my $rl (keys %$reverse_lookups) {
1032    $working_info->add_reverseinfo($rl,$oid);
1033    } 
1034
1035    # meta files not set in reverse entry, but need to set the metadata flag
1036    if (defined $doc_obj->get_meta_files()) {
1037    foreach my $meta_file_rec(@{$doc_obj->get_meta_files()}) {
1038        my $full_file = (ref $meta_file_rec eq "ARRAY") ? $meta_file_rec->[0] : $meta_file_rec;
1039        $working_info->set_meta_file_flag($full_file);
1040    }
1041    }
1042}
1043
1044# This sub is called for every metadata.xml accepted for processing by by MetdataXMLPlugin
1045# and adds an entry into archiveinf-src.db for that file in the form:
1046#   [@THISCOLLECTPATH@/import/metadata.xml]
1047#   <meta-file>1
1048# This prevents blind reprocessing of the same old docs upon *incremental* building whenever
1049# we encounter a default empty metadata.xml that has no actual <FileSet> content defined.
1050sub add_metaxml_file_entry_to_archiveinfsrc {
1051    my $self = shift (@_);
1052    my ($full_file) = @_;
1053   
1054    print STDERR "**** Adding metaxml file entry for full_file: $full_file\n";
1055    my $working_info = $self->{'output_info'};
1056    $working_info->set_meta_file_flag($full_file);
1057}
1058
1059
1060sub set_sortmeta {
1061    my $self = shift (@_);
1062    my ($sortmeta, $removeprefix, $removesuffix) = @_;
1063   
1064    $self->{'sortmeta'} = $sortmeta;
1065    if (defined ($removeprefix) && $removeprefix ) {
1066    $removeprefix =~ s/^\^//; # don't need a leading ^
1067    $self->{'removeprefix'} = $removeprefix;
1068    }
1069    if (defined ($removesuffix) && $removesuffix) {
1070    $removesuffix =~ s/\$$//; # don't need a trailing $
1071    $self->{'removesuffix'} = $removesuffix;
1072    }
1073}
1074
1075
1076
1077sub open_xslt_pipe
1078{
1079    my $self = shift @_;
1080    my ($output_file_name, $xslt_file)=@_;
1081
1082    return unless defined $xslt_file and $xslt_file ne "" and &FileUtils::fileExists($xslt_file);
1083   
1084    my $java_class_path =  &FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"bin","java","ApplyXSLT.jar");
1085
1086    my $mapping_file_path = "";
1087
1088    if ($ENV{'GSDLOS'} eq "windows"){
1089    $java_class_path .=";".&FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"bin","java","xalan.jar");
1090    # this file:/// bit didn't work for me on windows XP
1091    #$xslt_file = "\"file:///".$xslt_file."\"";
1092    #$mapping_file_path = "\"file:///";
1093    }
1094    else{
1095    $java_class_path .=":".&FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"bin","java","xalan.jar");
1096    }
1097
1098
1099    $java_class_path = "\"".$java_class_path."\"";
1100
1101    my $cmd = "| java -cp $java_class_path org.nzdl.gsdl.ApplyXSLT -t \"$xslt_file\" ";
1102
1103    if (defined $self->{'mapping_file'} and $self->{'mapping_file'} ne ""){
1104    my $mapping_file_path = "\"".$self->{'mapping_file'}."\"";
1105    $cmd .= "-m $mapping_file_path";
1106    }
1107   
1108    open(*XMLWRITER, $cmd)
1109    or die "can't open pipe to xslt: $!";
1110
1111   
1112    $self->{'xslt_writer'} = *XMLWRITER;
1113
1114    print XMLWRITER "<?DocStart?>\n";       
1115    print XMLWRITER "$output_file_name\n";
1116
1117 
1118  }
1119 
1120
1121sub close_xslt_pipe
1122{
1123  my $self = shift @_;
1124
1125 
1126  return unless defined $self->{'xslt_writer'} ;
1127   
1128  my $xsltwriter = $self->{'xslt_writer'};
1129 
1130  print $xsltwriter "<?DocEnd?>\n";
1131  close($xsltwriter);
1132
1133  undef $self->{'xslt_writer'};
1134
1135}
1136
1137
1138
1139#the subclass should implement this method if is_group method could return 1.
1140sub close_group_output{
1141   my $self = shift (@_);       
1142}
1143
1144sub is_group {
1145    my $self = shift (@_);
1146    return 0;       
1147}
1148
1149my $dc_set = { Title => 1,       
1150           Creator => 1,
1151           Subject => 1,
1152           Description => 1,
1153           Publisher => 1,
1154           Contributor => 1,
1155           Date => 1,
1156           Type => 1,
1157           Format => 1,
1158           Identifier => 1,
1159           Source => 1,
1160           Language => 1,
1161           Relation => 1,
1162           Coverage => 1,
1163           Rights => 1};
1164
1165
1166# returns an XML representation of the dublin core metadata
1167# if dc meta is not found, try ex meta
1168# This method is not used by the DSpacePlugout, which has its
1169# own method to save its dc metadata
1170sub get_dc_metadata {
1171    my $self = shift(@_);
1172    my ($doc_obj, $section, $version) = @_;
1173   
1174    # build up string of dublin core metadata
1175    $section="" unless defined $section;
1176   
1177    my $section_ptr = $doc_obj->_lookup_section($section);
1178    return "" unless defined $section_ptr;
1179
1180
1181    my $explicit_dc = {};
1182    my $explicit_ex_dc = {};
1183    my $explicit_ex = {};
1184
1185    my $all_text="";
1186   
1187    # We want high quality dc metadata to go in first, so we store all the
1188    # assigned dc.* values first. Then, for all those dc metadata names in
1189    # the official dc set that are as yet unassigned, we look to see whether
1190    # embedded ex.dc.* metadata has defined some values for them. If not,
1191    # then for the same missing dc metadata names, we look in ex metadata.
1192
1193    foreach my $data (@{$section_ptr->{'metadata'}}){
1194    my $escaped_value = &docprint::escape_text($data->[1]);
1195    if ($data->[0]=~ m/^dc\./) {
1196        $data->[0] =~ tr/[A-Z]/[a-z]/;
1197
1198        $data->[0] =~ m/^dc\.(.*)/;
1199        my $dc_element =  $1;
1200
1201        if (!defined $explicit_dc->{$dc_element}) {
1202        $explicit_dc->{$dc_element} = [];
1203        }
1204        push(@{$explicit_dc->{$dc_element}},$escaped_value);
1205
1206        if (defined $version && ($version eq "oai_dc")) {
1207        $all_text .= "   <dc:$dc_element>$escaped_value</dc:$dc_element>\n";
1208        }
1209        else {
1210        # qualifier???
1211        $all_text .= '   <dcvalue element="'. $dc_element.'">'. $escaped_value. "</dcvalue>\n";
1212        }
1213
1214    } elsif ($data->[0]=~ m/^ex\.dc\./) { # now look through ex.dc.* to fill in as yet unassigned fields in dc metaset
1215        $data->[0] =~ m/^ex\.dc\.(.*)/;
1216        my $ex_dc_element = $1;
1217        my $lc_ex_dc_element = lc($ex_dc_element);
1218
1219        # only store the ex.dc value for this dc metaname if no dc.* was assigned for it
1220        if (defined $dc_set->{$ex_dc_element}) {
1221        if (!defined $explicit_ex_dc->{$lc_ex_dc_element}) {
1222            $explicit_ex_dc->{$lc_ex_dc_element} = [];
1223        }
1224        push(@{$explicit_ex_dc->{$lc_ex_dc_element}},$escaped_value);
1225        }
1226    }
1227    elsif (($data->[0] =~ m/^ex\./) || ($data->[0] !~ m/\./)) { # look through ex. meta (incl. meta without prefix)
1228        $data->[0] =~ m/^(ex\.)?(.*)/;
1229        my $ex_element = $2;
1230        my $lc_ex_element = lc($ex_element);
1231
1232        if (defined $dc_set->{$ex_element}) {
1233        if (!defined $explicit_ex->{$lc_ex_element}) {
1234            $explicit_ex->{$lc_ex_element} = [];
1235        }
1236        push(@{$explicit_ex->{$lc_ex_element}},$escaped_value);
1237        }
1238    }
1239    }
1240
1241    # go through dc_set and for any element *not* defined in explicit_dc
1242    # that does exist in explicit_ex, add it in as metadata
1243    foreach my $k ( keys %$dc_set ) {
1244    my $lc_k = lc($k);
1245
1246    if (!defined $explicit_dc->{$lc_k}) {
1247        # try to find if ex.dc.* defines this dc.* meta,
1248        # if not, then look for whether there's an ex.* equivalent
1249
1250        if (defined $explicit_ex_dc->{$lc_k}) {
1251        foreach my $v (@{$explicit_ex_dc->{$lc_k}}) {
1252            my $dc_element    = $lc_k;
1253            my $escaped_value = $v;
1254           
1255            if (defined $version && ($version eq "oai_dc")) {
1256            $all_text .= "   <dc:$dc_element>$escaped_value</dc:$dc_element>\n";
1257            }
1258            else {
1259            $all_text .= '   <dcvalue element="'. $dc_element.'">'. $escaped_value. "</dcvalue>\n";
1260            }           
1261        }
1262        } elsif (defined $explicit_ex->{$lc_k}) {
1263        foreach my $v (@{$explicit_ex->{$lc_k}}) {
1264            my $dc_element    = $lc_k;
1265            my $escaped_value = $v;
1266
1267            if (defined $version && ($version eq "oai_dc")) {
1268            $all_text .= "   <dc:$dc_element>$escaped_value</dc:$dc_element>\n";
1269            }
1270            else {
1271            $all_text .= '   <dcvalue element="'. $dc_element.'">'. $escaped_value. "</dcvalue>\n";
1272            }
1273        }
1274        }
1275    }
1276    }
1277
1278    if ($all_text eq "") {
1279    $all_text .= "   There is no Dublin Core metatdata in this document\n";
1280    }   
1281    $all_text =~ s/[\x00-\x09\x0B\x0C\x0E-\x1F]//g;
1282
1283    return $all_text;
1284}
1285
1286# Build up dublin_core metadata.  Priority given to dc.* over ex.*
1287# This method was apparently added by Jeffrey and committed by Shaoqun.
1288# But we don't know why it was added, so not using it anymore.
1289sub new_get_dc_metadata {
1290   
1291    my $self = shift(@_);
1292    my ($doc_obj, $section, $version) = @_;
1293
1294    # build up string of dublin core metadata
1295    $section="" unless defined $section;
1296   
1297    my $section_ptr=$doc_obj->_lookup_section($section);
1298    return "" unless defined $section_ptr;
1299
1300    my $all_text = "";
1301    foreach my $data (@{$section_ptr->{'metadata'}}){
1302    my $escaped_value = &docprint::escape_text($data->[1]);
1303    my $dc_element =  $data->[0];
1304   
1305    my @array = split('\.',$dc_element);
1306    my ($type,$name);
1307
1308    if(defined $array[1])
1309    {
1310        $type = $array[0];
1311        $name = $array[1];
1312    }
1313    else
1314    {
1315        $type = "ex";
1316        $name = $array[0];
1317    }
1318   
1319    $all_text .= '   <Metadata Type="'. $type.'" Name="'.$name.'">'. $escaped_value. "</Metadata>\n";
1320    }
1321    return $all_text;
1322}
1323
1324
13251;
Note: See TracBrowser for help on using the browser.