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

Revision 32540, 38.3 KB (checked in by ak19, 22 months ago)

Modified BasePlugout? so that plugouts now take the site_name parameter, needed by GreenstoneSQLPlugout. Similar changes were made in the previous commit for plugins, where GreenstoneSQLPlugin needed to have access to site_name. In both cases, for GS2, the site_name (and hence SQL database name) is greenstone2.

  • 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# OIDtype may be "hash" or "hash_on_full_filename" or "incremental" or "filename" or "dirname" or "full_filename" or "assigned"
350sub set_OIDtype {
351    my $self = shift (@_);
352    my ($type, $metadata) = @_;
353
354    if ($type =~ /^(hash|hash_on_full_filename|incremental|filename|dirname|full_filename|assigned)$/) {
355    $self->{'OIDtype'} = $type;
356    } else {
357    $self->{'OIDtype'} = "hash";
358    }
359    if ($type =~ /^assigned$/) {
360    if (defined $metadata) {
361        $self->{'OIDmetadata'} = $metadata;
362    } else {
363        $self->{'OIDmetadata'} = "dc.Identifier";
364    }
365    }
366}
367
368sub set_output_dir
369{
370    my $self = shift @_;
371    my ($output_dir) = @_;
372
373   $self->{'output_dir'} = $output_dir;
374}
375
376sub setoutputdir
377{
378    my $self = shift @_;
379    my ($output_dir) = @_;
380
381    $self->{'output_dir'} = $output_dir;
382}
383
384sub get_output_dir
385{
386    my $self = shift (@_);
387
388   return $self->{'output_dir'};
389}
390
391sub getoutputdir
392{
393    my $self = shift (@_);
394
395    return $self->{'output_dir'};
396}
397
398sub getoutputinfo
399{
400    my $self = shift (@_);
401
402    return $self->{'output_info'};
403}
404
405
406sub get_output_handler
407{
408    my $self = shift (@_);
409
410    my ($output_file_name) = @_;
411
412    my $fh;
413    &FileUtils::openFileHandle($output_file_name, '>', \$fh) or die('Can not open a file handler for: ' . $output_file_name . "\n");
414
415    return $fh;
416}
417
418sub release_output_handler
419{
420    my $self = shift (@_);
421    my ($outhandler) = @_;
422
423    close($outhandler);
424
425}
426
427sub output_xml_header {
428    my $self = shift (@_);
429    my ($handle,$docroot,$nondoctype) = @_;
430   
431   
432    #print $handle '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . "\n";
433   
434    #For Dspace must be UTF in lower case
435    print $handle '<?xml version="1.0" encoding="utf-8" standalone="no"?>' . "\n";
436   
437    if (!defined $nondoctype){
438    my $doctype = (defined $docroot) ? $docroot : "Section";
439
440    # Used to be '<!DOCTYPE Archive SYSTEM ...'
441   
442    print $handle "<!DOCTYPE $doctype SYSTEM \"http://greenstone.org/dtd/Archive/1.0/Archive.dtd\">\n";
443    }
444
445    print $handle "<$docroot>\n" if defined $docroot;
446}
447
448sub output_xml_footer {
449    my $self = shift (@_);
450    my ($handle,$docroot) = @_;
451    print $handle "</$docroot>\n" if defined $docroot;
452}
453
454
455sub output_general_xml_header
456{
457    my $self = shift (@_);
458    my ($handle,$docroot,$opt_attributes,$opt_dtd, $opt_doctype) = @_;
459   
460    print $handle '<?xml version="1.0" encoding="utf-8" standalone="no"?>' . "\n";
461   
462    if (defined $opt_dtd) {
463        my $doctype = (defined $opt_doctype) ? $opt_doctype : $docroot;
464    print $handle "<!DOCTYPE $doctype SYSTEM \"$opt_dtd\">\n";
465    }
466
467    if (defined $docroot) {
468        my $full_docroot = $docroot;
469        if (defined $opt_attributes) {
470          $full_docroot .= " $opt_attributes";
471        }
472
473        print $handle "<$full_docroot>\n"
474      }
475}
476
477sub output_general_xml_footer
478{
479    output_xml_footer(@_);
480}
481
482# This is called by the plugins after read_into_doc_obj generates the doc_obj.
483sub process {
484    my $self = shift (@_);
485    my ($doc_obj) = @_;
486
487    my $output_info = $self->{'output_info'};
488    return if (!defined $output_info);
489
490    # for OAI purposes
491    $doc_obj->set_lastmodified();
492    $doc_obj->set_oailastmodified();
493
494    # find out which directory to save to
495    my $doc_dir = "";
496    if ($self->is_group()) {
497    $doc_dir = $self->get_group_doc_dir($doc_obj);     
498    } else {
499    $doc_dir = $self->get_doc_dir($doc_obj);
500    }
501     
502    ##############################
503    # call subclass' saveas method
504    ##############################
505    $self->saveas($doc_obj,$doc_dir);
506
507    # write out data to archiveinf-doc.db
508    if ($self->{'generate_databases'}) {
509    $self->archiveinf_db($doc_obj);
510    }
511    if ($self->is_group()) {
512    $self->{'gs_count'}++; # do we want this for all cases?
513    $self->{'group_position'}++;
514    }
515}
516
517sub store_output_info_reference {
518    my $self = shift (@_);
519    my ($doc_obj) = @_;
520
521    my $output_info = $self->{'output_info'};
522    my $metaname = $self->{'sortmeta'};
523
524    my $group_position;
525    if ($self->is_group()) {
526    $group_position = $self->{'group_position'};
527    }
528    if (!defined $metaname || $metaname !~ /\S/) {
529    my $OID = $doc_obj->get_OID();
530    $output_info->add_info($OID,$self->{'short_doc_file'}, undef, "", $group_position);
531    return;
532    }
533   
534    if ($metaname eq "OID") { # sort by OID
535    my $OID = $doc_obj->get_OID();
536    $output_info->add_info($OID,$self->{'short_doc_file'}, undef, $OID, undef);
537    return;
538    }
539   
540    my $metadata = "";
541    my $top_section = $doc_obj->get_top_section();
542   
543    my @commameta_list = split(/,/, $metaname);
544    foreach my $cmn (@commameta_list) {
545    my $meta = $doc_obj->get_metadata_element($top_section, $cmn);
546    if ($meta) {
547        # do remove prefix/suffix - this will apply to all values
548        $meta =~ s/^$self->{'removeprefix'}// if defined $self->{'removeprefix'};         
549        $meta =~ s/$self->{'removesuffix'}$// if defined $self->{'removesuffix'};
550        $meta = &sorttools::format_metadata_for_sorting($cmn, $meta, $doc_obj);
551        $metadata .= $meta if ($meta);
552    }
553    }
554
555    # store reference in the output_info     
556    $output_info->add_info($doc_obj->get_OID(),$self->{'short_doc_file'}, undef, $metadata,undef);
557   
558}
559
560
561
562sub saveas {
563    my $self = shift (@_);
564    my ($doc_obj, $doc_dir) = @_;
565   
566    die "Basplug::saveas function must be implemented in sub classes\n";
567}
568
569sub get_group_doc_dir {
570    my $self = shift (@_);
571    my ($doc_obj) = @_;
572
573    my $outhandle = $self->{'output_handle'};
574    my $OID = $doc_obj->get_OID();
575    $OID = "NULL" unless defined $OID;
576
577    my $groupsize = $self->{'group_size'};
578    my $gs_count = $self->{'gs_count'};
579    my $open_new_file = (($gs_count % $groupsize)==0);
580
581    my $doc_dir;
582
583    if (!$open_new_file && scalar(@{$doc_obj->get_assoc_files()})>0) {
584    # if we have some assoc files, then we will need to start a new file
585    if ($self->{'verbosity'} > 2) {
586        print $outhandle " Starting a archives folder for $OID as it has associated files\n";
587    }
588    $open_new_file = 1;
589    }
590   
591    # opening a new file
592    if (($open_new_file)  || !defined($self->{'gs_doc_dir'})) {
593    # first we close off the old output
594    if ($gs_count>0)
595    {
596        return if (!$self->close_group_output());
597    }
598
599    # this will create the directory
600    $doc_dir = $self->get_doc_dir ($doc_obj);
601    $self->{'new_doc_dir'} = 1;
602    $self->{'gs_doc_dir'} = $doc_dir;
603    $self->{'group_position'} = 1;
604    }
605    else {
606    $doc_dir = $self->{'gs_doc_dir'};
607    $self->{'new_doc_dir'} = 0;
608    }
609    return $doc_dir;
610
611}
612sub get_doc_dir {
613   
614    my $self = shift (@_);
615    my ($doc_obj) = @_;
616
617    my $OID = $doc_obj->get_OID();
618    $OID = "NULL" unless defined $OID;
619
620    my $working_dir  = $self->get_output_dir();
621    my $working_info = $self->{'output_info'};
622    return if (!defined $working_info);
623
624    my $doc_info = $working_info->get_info($OID);
625    my $doc_dir = '';
626
627    if (defined $doc_info && scalar(@$doc_info) >= 1)
628    {
629    # This OID already has an archives directory, so use it again
630    $doc_dir = $doc_info->[0];
631    $doc_dir =~ s/\/?((doc(mets)?)|(dublin_core))\.xml(\.gz)?$//;
632    }
633    elsif ($self->{'keep_import_structure'})
634    {
635    my $source_filename = $doc_obj->get_source_filename();
636    $source_filename = &File::Basename::dirname($source_filename);
637    $source_filename =~ s/[\\\/]+/\//g;
638    $source_filename =~ s/\/$//;
639
640        $doc_dir = substr($source_filename, length($ENV{'GSDLIMPORTDIR'}) + 1);
641    }
642
643    # We have to use a new archives directory for this document
644    if ($doc_dir eq "")
645    {
646    $doc_dir = $self->get_new_doc_dir ($working_info, $working_dir, $OID);
647    }
648
649    &FileUtils::makeAllDirectories(&FileUtils::filenameConcatenate($working_dir, $doc_dir));
650
651    return $doc_dir;
652}
653
654
655## @function get_new_doc_dir()
656#
657# Once a doc object is ready to write to disk (and hence has a nice OID),
658# generate a unique subdirectory to write the information to.
659#
660# - create the directory as part of this call, to try and avoid race conditions
661#   found in parallel processing [jmt12]
662#
663# @todo figure out what the rule regarding $work_info->size() is meant to do
664#
665# @todo determine what $self->{'group'} is, and whether it should affect
666#       directory creation
667#
668sub get_new_doc_dir
669{
670  my $self = shift (@_);
671  my($working_info,$working_dir,$OID) = @_;
672
673  my $doc_dir = "";
674  my $doc_dir_rest = $OID;
675
676  # remove any \ and / from the OID
677  $doc_dir_rest =~ s/[\\\/]//g;
678
679  # Remove ":" if we are on Windows OS, as otherwise they get confused with the drive letters
680  if ($ENV{'GSDLOS'} =~ /^windows$/i)
681  {
682    $doc_dir_rest =~ s/\://g;
683  }
684
685  # we generally create a unique directory by adding consequtive fragments of
686  # the document identifier (split by some predefined length - defaulting to
687  # 8) until we find a directory that doesn't yet exist. Note that directories
688  # that contain a document have a suffix ".dir" (whereas those that contain
689  # only subdirectories have no suffix).
690  my $doc_dir_num = 0; # how many directories deep we are
691  my $created_directory = 0; # have we successfully created a new directory
692  do
693  {
694    # (does this work on windows? - jmt12)
695    if ($doc_dir_num > 0)
696    {
697      $doc_dir .= '/';
698    }
699
700    # the default matching pattern grabs the next 'subdir_split_length'
701    # characters of the OID to act as the next subdirectory
702    my $pattern = '^(.{1,' . $self->{'subdir_split_length'} . '})';
703
704    # Do we count any "HASH" prefix against the split length limit?
705    if ($self->{'subdir_hash_prefix'} && $doc_dir_num == 0)
706    {
707      $pattern = '^((HASH)?.{1,' . $self->{'subdir_split_length'} . '})';
708    }
709
710    # Note the use of 's' to both capture the next chuck of OID and to remove
711    # it from OID at the same time
712    if ($doc_dir_rest =~ s/$pattern//i)
713    {
714      $doc_dir .= $1;
715      $doc_dir_num++;
716
717      my $full_doc_dir = &FileUtils::filenameConcatenate($working_dir, $doc_dir . '.dir');
718      if(!FileUtils::directoryExists($full_doc_dir))
719      {
720        &FileUtils::makeAllDirectories($full_doc_dir);
721        $created_directory = 1;
722      }
723
724      ###rint STDERR "[DEBUG] BasePlugout::get_new_doc_dir(<working_info>, $working_dir, $oid)\n";
725      ###rint STDERR " - create directory: $full_doc_dir => $created_directory\n";
726      ###rint STDERR " - rest: $doc_dir_rest\n";
727      ###rint STDERR " - working_info->size(): " . $working_info->size() . " [ < 1024 ?]\n";
728      ###rint STDERR " - doc_dir_num: " . $doc_dir_num . "\n";
729    }
730  }
731  while ($doc_dir_rest ne '' && ($created_directory == 0 || ($working_info->size() >= 1024 && $doc_dir_num < 2)));
732
733  # not unique yet? Add on an incremental suffix until we are unique
734  my $i = 1;
735  my $doc_dir_base = $doc_dir;
736  while ($created_directory == 0)
737  {
738    $doc_dir = $doc_dir_base . '-' . $i;
739    $created_directory = &FileUtils::makeAllDirectories(&FileUtils::filenameConcatenate($working_dir, $doc_dir . '.dir'));
740    $i++;
741  }
742
743  # in theory this should never happen
744  if (!$created_directory)
745  {
746    die("Error! Failed to create directory for document: " . $doc_dir_base . "\n");
747  }
748
749  return $doc_dir . '.dir';
750}
751## get_new_doc_dir()
752
753
754sub process_assoc_files {
755    my $self = shift (@_);
756    my ($doc_obj, $doc_dir, $handle) = @_;
757
758    my $outhandle = $self->{'output_handle'};
759   
760    my $output_dir = $self->get_output_dir();
761    return if (!defined $output_dir);
762
763    &FileUtils::makeAllDirectories($output_dir) unless &FileUtils::directoryExists($output_dir);
764     
765    my $working_dir = &FileUtils::filenameConcatenate($output_dir, $doc_dir);
766    &FileUtils::makeAllDirectories($working_dir) unless &FileUtils::directoryExists($working_dir);
767
768    my @assoc_files = ();
769    my $filename;;
770
771    my $source_filename = $doc_obj->get_source_filename();
772
773    my $collect_dir = $ENV{'GSDLCOLLECTDIR'};
774
775    if (defined $collect_dir) {
776    my $dirsep_regexp = &util::get_os_dirsep();
777
778    if ($collect_dir !~ /$dirsep_regexp$/) {
779        $collect_dir .= &util::get_dirsep(); # ensure there is a slash at the end
780    }
781
782    # This test is never going to fail on Windows -- is this a problem?
783     
784    if ($source_filename !~ /^$dirsep_regexp/) {
785        $source_filename = &FileUtils::filenameConcatenate($collect_dir, $source_filename);
786    }
787    }
788
789
790    # set the assocfile path (even if we have no assoc files - need this for lucene)
791    $doc_obj->set_utf8_metadata_element ($doc_obj->get_top_section(),
792                     "assocfilepath",
793                     "$doc_dir");
794    foreach my $assoc_file_rec (@{$doc_obj->get_assoc_files()}) {
795    my ($dir, $afile) = $assoc_file_rec->[1] =~ /^(.*?)([^\/\\]+)$/;
796    $dir = "" unless defined $dir;
797       
798    my $utf8_real_filename = $assoc_file_rec->[0];
799
800    # for some reasons the image associate file has / before the full path
801    $utf8_real_filename =~ s/^\\(.*)/$1/i;
802
803##  my $real_filename = &util::utf8_to_real_filename($utf8_real_filename);
804    my $real_filename = $utf8_real_filename;
805    $real_filename = &util::downgrade_if_dos_filename($real_filename);
806
807    if (&FileUtils::fileExists($real_filename)) {
808
809        $filename = &FileUtils::filenameConcatenate($working_dir, $afile);
810
811            &FileUtils::hardLink($real_filename, $filename, $self->{'verbosity'});
812
813        $doc_obj->add_utf8_metadata ($doc_obj->get_top_section(),
814                     "gsdlassocfile",
815                     "$afile:$assoc_file_rec->[2]:$dir");
816    } elsif ($self->{'verbosity'} > 1) {
817        print $outhandle "BasePlugout::process couldn't copy the associated file " .
818        "$real_filename to $afile\n";
819    }
820    }
821}
822
823
824sub process_metafiles_metadata
825{
826    my $self = shift (@_);
827    my ($doc_obj) = @_;
828
829    my $top_section = $doc_obj->get_top_section();
830    my $metafiles = $doc_obj->get_metadata($top_section,"gsdlmetafile");
831
832    foreach my $metafile_pair (@$metafiles) {
833    my ($full_metafile,$metafile) = split(/ : /,$metafile_pair);
834
835    $doc_obj->metadata_file($full_metafile,$metafile);
836    }
837
838    $doc_obj->delete_metadata($top_section,"gsdlmetafile");
839}
840
841sub archiveinf_files_to_field
842{
843    my $self = shift(@_);
844    my ($files,$field,$collect_dir,$oid_files,$reverse_lookups) = @_;
845
846    foreach my $file_rec (@$files) {
847    my $real_filename = (ref $file_rec eq "ARRAY") ? $file_rec->[0] : $file_rec;
848    my $full_file = (ref $file_rec eq "ARRAY") ? $file_rec->[1] : $file_rec;
849    # for some reasons the image associate file has / before the full path
850    $real_filename =~ s/^\\(.*)/$1/i;
851
852    my $raw_filename = &util::downgrade_if_dos_filename($real_filename);
853
854    if (&FileUtils::fileExists($raw_filename)) {
855
856#       if (defined $collect_dir) {
857#       my $collect_dir_re_safe = $collect_dir;
858#       $collect_dir_re_safe =~ s/\\/\\\\/g; # use &util::filename_to_regex()
859#       $collect_dir_re_safe =~ s/\./\\./g;##
860
861#       $real_filename =~ s/^$collect_dir_re_safe//;
862#       }
863       
864        if (defined $reverse_lookups) {
865        $reverse_lookups->{$real_filename} = 1;
866        }
867
868        if($field =~ m@assoc-file|src-file|meta-file@) {
869        $raw_filename = &util::abspath_to_placeholders($raw_filename);
870        }
871
872###     push(@{$oid_files->{$field}},$full_file);       
873        push(@{$oid_files->{$field}},$raw_filename);
874    }
875    else {
876        print STDERR "Warning: archiveinf_files_to_field()\n  $real_filename does not appear to be on the file system\n";
877    }
878    }
879}
880
881sub archiveinf_db
882{
883    my $self = shift (@_);
884    my ($doc_obj) = @_;
885
886    my $verbosity = $self->{'verbosity'};
887
888    my $collect_dir = $ENV{'GSDLCOLLECTDIR'};
889    if (defined $collect_dir) {
890    my $dirsep_regexp = &util::get_os_dirsep();
891
892    if ($collect_dir !~ /$dirsep_regexp$/) {
893        # ensure there is a slash at the end
894        $collect_dir .= &util::get_dirsep();
895    }
896    }
897
898    my $oid = $doc_obj->get_OID();
899    my $source_filename = $doc_obj->get_unmodified_source_filename();
900    my $working_info = $self->{'output_info'};
901    my $doc_info = $working_info->get_info($oid);
902
903    my ($doc_file,$index_status,$sortmeta, $group_position) = @$doc_info;
904    # doc_file is the path to the archive doc.xml. Make sure it has unix
905    # slashes, then if the collection is copied to linux, it can be built without reimport
906    $doc_file =~ s/\\/\//g;
907    my $oid_files = { 'doc-file' => $doc_file,
908              'index-status' => $index_status,
909              'src-file' => $source_filename,
910              'sort-meta' => $sortmeta,
911              'assoc-file' => [],
912              'meta-file'  => [] };
913    if (defined $group_position) {
914    $oid_files->{'group-position'} = $group_position;
915    }
916    my $reverse_lookups = { $source_filename => "1" };
917
918
919    $self->archiveinf_files_to_field($doc_obj->get_source_assoc_files(),"assoc-file",
920                     $collect_dir,$oid_files,$reverse_lookups);
921
922
923    $self->archiveinf_files_to_field($doc_obj->get_meta_files(),"meta-file",
924                     $collect_dir,$oid_files);
925
926    # Get the infodbtype value for this collection from the arcinfo object
927    my $infodbtype = $self->{'output_info'}->{'infodbtype'};
928    my $output_dir = $self->{'output_dir'};
929
930    my $doc_db = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $output_dir);
931
932    ##print STDERR "*** To set in db: \n\t$doc_db\n\t$oid\n\t$doc_db_text\n";
933
934    if (!$self->{'no_rss'})
935    {
936      if (($oid_files->{'index-status'} eq "I") || ($oid_files->{'index-status'} eq "R")) {
937    my $top_section = $doc_obj->get_top_section();
938   
939    # rss_title can be set in collect.cfg as follows:
940    #      plugout GreenstoneXMLPlugout -rss_title "dc.Title; ex.Title"
941    # rss_title is a semi-colon or comma-separated list of the metadata field names that should
942    # be consulted in order to obtain a Title (anchor text) for the RSS document link.   
943    # If not specified, rss_title will default to dc.Title, and fall back on Untitled
944    my $metafieldnames = $self->{'rss_title'};
945    my @metafieldarray = split(/[,;] ?/,$metafieldnames); # , or ; separator can be followed by an optional space
946    my $titles;
947    #@$titles=(); # at worst @$titles will be (), as get_metadata(dc.Titles) may return ()
948    foreach my $metafieldname (@metafieldarray) {
949        $metafieldname =~ s@^ex\.@@; # if ex.Title, need to get_metadata() on metafieldname=Title
950        $titles = $doc_obj->get_metadata($top_section,$metafieldname);
951
952        if(scalar(@$titles) != 0) { # found at least one title for one metafieldname
953           last; # break out of the loop
954        }
955    }
956   
957    # if ex.Title was listed in the metafieldnames, then we'll surely have a value for title for this doc
958    # otherwise, if we have no titles at this point, add in a default of Untitled as this doc's title
959    if(scalar(@$titles) == 0) { #&& $metafieldnames !~ m@ex.Title@) {
960        push(@$titles, "Untitled");
961    }
962   
963    # encode basic html entities like <>"& in the title(s), since the & char can break RSS links
964    for (my $i = 0; $i < scalar(@$titles); $i++) {
965        &ghtml::htmlsafe(@$titles[$i]);
966    }
967
968    my $dc_title = join("; ", @$titles);
969
970    if ($oid_files->{'index-status'} eq "R") {
971        $dc_title .= " (Updated)";
972    }
973
974        my $rss_entry = "<item>\n";
975        $rss_entry   .= "   <title>$dc_title</title>\n";
976    if(&util::is_gs3()) {
977        $rss_entry   .= "   <link>_httpdomain__httpcollection_/document/$oid</link>\n";
978    } else {
979        $rss_entry   .= "   <link>_httpdomainHtmlsafe__httpcollection_/document/$oid</link>\n";
980    }
981    $rss_entry   .= "</item>";
982
983        if (defined(&dbutil::supportsRSS) && &dbutil::supportsRSS($infodbtype))
984        {
985          my $rss_db = &dbutil::get_infodb_file_path($infodbtype, 'rss-items', $output_dir);
986          my $rss_db_fh = &dbutil::open_infodb_write_handle($infodbtype, $rss_db, 'append');
987          &dbutil::write_infodb_rawentry($infodbtype, $rss_db_fh, $oid, $rss_entry);
988          &dbutil::close_infodb_write_handle($infodbtype, $rss_db_fh);
989        }
990        else
991        {
992          my $rss_filename = &FileUtils::filenameConcatenate($output_dir,"rss-items.rdf");
993          my $rss_fh;
994          if (&FileUtils::openFileHandle($rss_filename, '>>', \$rss_fh, "utf8"))
995          {
996        print $rss_fh $rss_entry . "\n";
997        &FileUtils::closeFileHandle($rss_filename, \$rss_fh);
998          }
999          else
1000          {
1001        print STDERR "**** Failed to open $rss_filename\n$!\n";
1002          }
1003        }
1004      }
1005    }
1006
1007    $oid_files->{'doc-file'} = [ $oid_files->{'doc-file'} ];
1008    $oid_files->{'index-status'} = [ $oid_files->{'index-status'} ];
1009    $oid_files->{'src-file'} = &util::abspath_to_placeholders($oid_files->{'src-file'});
1010    $oid_files->{'src-file'} = [ $oid_files->{'src-file'} ];
1011    $oid_files->{'sort-meta'} = [ $oid_files->{'sort-meta'} ];
1012    if (defined $oid_files->{'group-position'}) {
1013    $oid_files->{'group-position'} = [ $oid_files->{'group-position'} ];
1014    }
1015
1016    my $infodb_file_handle = &dbutil::open_infodb_write_handle($infodbtype, $doc_db, "append");
1017    &dbutil::write_infodb_entry($infodbtype, $infodb_file_handle, $oid, $oid_files);
1018    &dbutil::close_infodb_write_handle($infodbtype, $infodb_file_handle);
1019
1020    foreach my $rl (keys %$reverse_lookups) {
1021    $working_info->add_reverseinfo($rl,$oid);
1022    } 
1023
1024    # meta files not set in reverse entry, but need to set the metadata flag
1025    if (defined $doc_obj->get_meta_files()) {
1026    foreach my $meta_file_rec(@{$doc_obj->get_meta_files()}) {
1027        my $full_file = (ref $meta_file_rec eq "ARRAY") ? $meta_file_rec->[0] : $meta_file_rec;
1028        $working_info->set_meta_file_flag($full_file);
1029    }
1030    }
1031}
1032
1033# This sub is called for every metadata.xml accepted for processing by by MetdataXMLPlugin
1034# and adds an entry into archiveinf-src.db for that file in the form:
1035#   [@THISCOLLECTPATH@/import/metadata.xml]
1036#   <meta-file>1
1037# This prevents blind reprocessing of the same old docs upon *incremental* building whenever
1038# we encounter a default empty metadata.xml that has no actual <FileSet> content defined.
1039sub add_metaxml_file_entry_to_archiveinfsrc {
1040    my $self = shift (@_);
1041    my ($full_file) = @_;
1042   
1043    print STDERR "**** Adding metaxml file entry for full_file: $full_file\n";
1044    my $working_info = $self->{'output_info'};
1045    $working_info->set_meta_file_flag($full_file);
1046}
1047
1048
1049sub set_sortmeta {
1050    my $self = shift (@_);
1051    my ($sortmeta, $removeprefix, $removesuffix) = @_;
1052   
1053    $self->{'sortmeta'} = $sortmeta;
1054    if (defined ($removeprefix) && $removeprefix ) {
1055    $removeprefix =~ s/^\^//; # don't need a leading ^
1056    $self->{'removeprefix'} = $removeprefix;
1057    }
1058    if (defined ($removesuffix) && $removesuffix) {
1059    $removesuffix =~ s/\$$//; # don't need a trailing $
1060    $self->{'removesuffix'} = $removesuffix;
1061    }
1062}
1063
1064
1065
1066sub open_xslt_pipe
1067{
1068    my $self = shift @_;
1069    my ($output_file_name, $xslt_file)=@_;
1070
1071    return unless defined $xslt_file and $xslt_file ne "" and &FileUtils::fileExists($xslt_file);
1072   
1073    my $java_class_path =  &FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"bin","java","ApplyXSLT.jar");
1074
1075    my $mapping_file_path = "";
1076
1077    if ($ENV{'GSDLOS'} eq "windows"){
1078    $java_class_path .=";".&FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"bin","java","xalan.jar");
1079    # this file:/// bit didn't work for me on windows XP
1080    #$xslt_file = "\"file:///".$xslt_file."\"";
1081    #$mapping_file_path = "\"file:///";
1082    }
1083    else{
1084    $java_class_path .=":".&FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"bin","java","xalan.jar");
1085    }
1086
1087
1088    $java_class_path = "\"".$java_class_path."\"";
1089
1090    my $cmd = "| java -cp $java_class_path org.nzdl.gsdl.ApplyXSLT -t \"$xslt_file\" ";
1091
1092    if (defined $self->{'mapping_file'} and $self->{'mapping_file'} ne ""){
1093    my $mapping_file_path = "\"".$self->{'mapping_file'}."\"";
1094    $cmd .= "-m $mapping_file_path";
1095    }
1096   
1097    open(*XMLWRITER, $cmd)
1098    or die "can't open pipe to xslt: $!";
1099
1100   
1101    $self->{'xslt_writer'} = *XMLWRITER;
1102
1103    print XMLWRITER "<?DocStart?>\n";       
1104    print XMLWRITER "$output_file_name\n";
1105
1106 
1107  }
1108 
1109
1110sub close_xslt_pipe
1111{
1112  my $self = shift @_;
1113
1114 
1115  return unless defined $self->{'xslt_writer'} ;
1116   
1117  my $xsltwriter = $self->{'xslt_writer'};
1118 
1119  print $xsltwriter "<?DocEnd?>\n";
1120  close($xsltwriter);
1121
1122  undef $self->{'xslt_writer'};
1123
1124}
1125
1126
1127
1128#the subclass should implement this method if is_group method could return 1.
1129sub close_group_output{
1130   my $self = shift (@_);       
1131}
1132
1133sub is_group {
1134    my $self = shift (@_);
1135    return 0;       
1136}
1137
1138my $dc_set = { Title => 1,       
1139           Creator => 1,
1140           Subject => 1,
1141           Description => 1,
1142           Publisher => 1,
1143           Contributor => 1,
1144           Date => 1,
1145           Type => 1,
1146           Format => 1,
1147           Identifier => 1,
1148           Source => 1,
1149           Language => 1,
1150           Relation => 1,
1151           Coverage => 1,
1152           Rights => 1};
1153
1154
1155# returns an XML representation of the dublin core metadata
1156# if dc meta is not found, try ex meta
1157# This method is not used by the DSpacePlugout, which has its
1158# own method to save its dc metadata
1159sub get_dc_metadata {
1160    my $self = shift(@_);
1161    my ($doc_obj, $section, $version) = @_;
1162   
1163    # build up string of dublin core metadata
1164    $section="" unless defined $section;
1165   
1166    my $section_ptr = $doc_obj->_lookup_section($section);
1167    return "" unless defined $section_ptr;
1168
1169
1170    my $explicit_dc = {};
1171    my $explicit_ex_dc = {};
1172    my $explicit_ex = {};
1173
1174    my $all_text="";
1175   
1176    # We want high quality dc metadata to go in first, so we store all the
1177    # assigned dc.* values first. Then, for all those dc metadata names in
1178    # the official dc set that are as yet unassigned, we look to see whether
1179    # embedded ex.dc.* metadata has defined some values for them. If not,
1180    # then for the same missing dc metadata names, we look in ex metadata.
1181
1182    foreach my $data (@{$section_ptr->{'metadata'}}){
1183    my $escaped_value = &docprint::escape_text($data->[1]);
1184    if ($data->[0]=~ m/^dc\./) {
1185        $data->[0] =~ tr/[A-Z]/[a-z]/;
1186
1187        $data->[0] =~ m/^dc\.(.*)/;
1188        my $dc_element =  $1;
1189
1190        if (!defined $explicit_dc->{$dc_element}) {
1191        $explicit_dc->{$dc_element} = [];
1192        }
1193        push(@{$explicit_dc->{$dc_element}},$escaped_value);
1194
1195        if (defined $version && ($version eq "oai_dc")) {
1196        $all_text .= "   <dc:$dc_element>$escaped_value</dc:$dc_element>\n";
1197        }
1198        else {
1199        # qualifier???
1200        $all_text .= '   <dcvalue element="'. $dc_element.'">'. $escaped_value. "</dcvalue>\n";
1201        }
1202
1203    } elsif ($data->[0]=~ m/^ex\.dc\./) { # now look through ex.dc.* to fill in as yet unassigned fields in dc metaset
1204        $data->[0] =~ m/^ex\.dc\.(.*)/;
1205        my $ex_dc_element = $1;
1206        my $lc_ex_dc_element = lc($ex_dc_element);
1207
1208        # only store the ex.dc value for this dc metaname if no dc.* was assigned for it
1209        if (defined $dc_set->{$ex_dc_element}) {
1210        if (!defined $explicit_ex_dc->{$lc_ex_dc_element}) {
1211            $explicit_ex_dc->{$lc_ex_dc_element} = [];
1212        }
1213        push(@{$explicit_ex_dc->{$lc_ex_dc_element}},$escaped_value);
1214        }
1215    }
1216    elsif (($data->[0] =~ m/^ex\./) || ($data->[0] !~ m/\./)) { # look through ex. meta (incl. meta without prefix)
1217        $data->[0] =~ m/^(ex\.)?(.*)/;
1218        my $ex_element = $2;
1219        my $lc_ex_element = lc($ex_element);
1220
1221        if (defined $dc_set->{$ex_element}) {
1222        if (!defined $explicit_ex->{$lc_ex_element}) {
1223            $explicit_ex->{$lc_ex_element} = [];
1224        }
1225        push(@{$explicit_ex->{$lc_ex_element}},$escaped_value);
1226        }
1227    }
1228    }
1229
1230    # go through dc_set and for any element *not* defined in explicit_dc
1231    # that does exist in explicit_ex, add it in as metadata
1232    foreach my $k ( keys %$dc_set ) {
1233    my $lc_k = lc($k);
1234
1235    if (!defined $explicit_dc->{$lc_k}) {
1236        # try to find if ex.dc.* defines this dc.* meta,
1237        # if not, then look for whether there's an ex.* equivalent
1238
1239        if (defined $explicit_ex_dc->{$lc_k}) {
1240        foreach my $v (@{$explicit_ex_dc->{$lc_k}}) {
1241            my $dc_element    = $lc_k;
1242            my $escaped_value = $v;
1243           
1244            if (defined $version && ($version eq "oai_dc")) {
1245            $all_text .= "   <dc:$dc_element>$escaped_value</dc:$dc_element>\n";
1246            }
1247            else {
1248            $all_text .= '   <dcvalue element="'. $dc_element.'">'. $escaped_value. "</dcvalue>\n";
1249            }           
1250        }
1251        } elsif (defined $explicit_ex->{$lc_k}) {
1252        foreach my $v (@{$explicit_ex->{$lc_k}}) {
1253            my $dc_element    = $lc_k;
1254            my $escaped_value = $v;
1255
1256            if (defined $version && ($version eq "oai_dc")) {
1257            $all_text .= "   <dc:$dc_element>$escaped_value</dc:$dc_element>\n";
1258            }
1259            else {
1260            $all_text .= '   <dcvalue element="'. $dc_element.'">'. $escaped_value. "</dcvalue>\n";
1261            }
1262        }
1263        }
1264    }
1265    }
1266
1267    if ($all_text eq "") {
1268    $all_text .= "   There is no Dublin Core metatdata in this document\n";
1269    }   
1270    $all_text =~ s/[\x00-\x09\x0B\x0C\x0E-\x1F]//g;
1271
1272    return $all_text;
1273}
1274
1275# Build up dublin_core metadata.  Priority given to dc.* over ex.*
1276# This method was apparently added by Jeffrey and committed by Shaoqun.
1277# But we don't know why it was added, so not using it anymore.
1278sub new_get_dc_metadata {
1279   
1280    my $self = shift(@_);
1281    my ($doc_obj, $section, $version) = @_;
1282
1283    # build up string of dublin core metadata
1284    $section="" unless defined $section;
1285   
1286    my $section_ptr=$doc_obj->_lookup_section($section);
1287    return "" unless defined $section_ptr;
1288
1289    my $all_text = "";
1290    foreach my $data (@{$section_ptr->{'metadata'}}){
1291    my $escaped_value = &docprint::escape_text($data->[1]);
1292    my $dc_element =  $data->[0];
1293   
1294    my @array = split('\.',$dc_element);
1295    my ($type,$name);
1296
1297    if(defined $array[1])
1298    {
1299        $type = $array[0];
1300        $name = $array[1];
1301    }
1302    else
1303    {
1304        $type = "ex";
1305        $name = $array[0];
1306    }
1307   
1308    $all_text .= '   <Metadata Type="'. $type.'" Name="'.$name.'">'. $escaped_value. "</Metadata>\n";
1309    }
1310    return $all_text;
1311}
1312
1313
13141;
Note: See TracBrowser for help on using the browser.