source: main/trunk/greenstone2/perllib/plugouts/BasePlugout.pm@ 32511

Last change on this file since 32511 was 32511, checked in by ak19, 6 years ago

Running plugoutinfo.pl with describeall or listall flag would break on FedoraMETSPlugout when either FEDORA_HOME or FEDORA_VERSION aren't set (as is often the case), as there's a die statement in the BEGIN of FedoraMETSPlugout. Needed to run die if either FEDORA env var is not set only if the plugout is NOT in info_only mode in plugout constructor. However, info_only mode was never set in any of the plugouts, so had to add set up the infrastructure for it in plugoutinfo.pl and plugout.pm. Then added the info_only test to all teh plugouts, even though it's redundant in most of them for making sure future changes to any plugout's constructors does not break plugoutinfo.pl.

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