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

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

Added BasePlugout::end() so I can use it in the new MySQLPlugout, and which can mirrour BasePlugout::begin().

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