source: main/trunk/greenstone2/perllib/plugins/BasePlugin.pm@ 31457

Last change on this file since 31457 was 31457, checked in by kjdon, 7 years ago

baseplugin now inherits from EncodingUtil, and all its encoding methods have been moved to the new plugin

  • Property svn:keywords set to Author Date Id Revision
File size: 33.9 KB
Line 
1###########################################################################
2#
3# BasePlugin.pm -- base class for all the import plugins
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 1999-2005 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 BasePlugin;
27
28use strict;
29no strict 'subs';
30no strict 'refs'; # allow filehandles to be variables and viceversa
31
32use File::Basename;
33use Encode;
34use Unicode::Normalize 'normalize';
35
36use encodings;
37use unicode;
38use doc;
39use ghtml;
40use gsprintf 'gsprintf';
41use util;
42use FileUtils;
43
44use EncodingUtil;
45
46BEGIN {
47 @BasePlugin::ISA = ( 'EncodingUtil' );
48}
49
50# the different methods that can be applied when renaming
51# imported documents and their associated files
52our $file_rename_method_list =
53 [ { 'name' => "url",
54 'desc' => "{BasePlugin.rename_method.url}" },
55 { 'name' => "base64",
56 'desc' => "{BasePlugin.rename_method.base64}" },
57 { 'name' => "none",
58 'desc' => "{BasePlugin.rename_method.none}",
59 'hiddengli' => "yes" } ];
60
61# here went encoding list stuff
62
63our $oidtype_list =
64 [ { 'name' => "auto",
65 'desc' => "{BasePlugin.OIDtype.auto}" },
66 { 'name' => "hash",
67 'desc' => "{import.OIDtype.hash}" },
68 { 'name' => "hash_on_ga_xml",
69 'desc' => "{import.OIDtype.hash_on_ga_xml}" },
70 { 'name' => "hash_on_full_filename",
71 'desc' => "{import.OIDtype.hash_on_full_filename}" },
72 { 'name' => "assigned",
73 'desc' => "{import.OIDtype.assigned}" },
74 { 'name' => "incremental",
75 'desc' => "{import.OIDtype.incremental}" },
76 { 'name' => "filename",
77 'desc' => "{import.OIDtype.filename}" },
78 { 'name' => "dirname",
79 'desc' => "{import.OIDtype.dirname}" },
80 { 'name' => "full_filename",
81 'desc' => "{import.OIDtype.full_filename}" } ];
82
83my $arguments =
84 [ { 'name' => "process_exp",
85 'desc' => "{BasePlugin.process_exp}",
86 'type' => "regexp",
87 'deft' => "",
88 'reqd' => "no" },
89 { 'name' => "no_blocking",
90 'desc' => "{BasePlugin.no_blocking}",
91 'type' => "flag",
92 'reqd' => "no"},
93 { 'name' => "block_exp",
94 'desc' => "{BasePlugin.block_exp}",
95 'type' => "regexp",
96 'deft' => "",
97 'reqd' => "no" },
98 { 'name' => "store_original_file",
99 'desc' => "{BasePlugin.store_original_file}",
100 'type' => "flag",
101 'reqd' => "no" },
102 { 'name' => "associate_ext",
103 'desc' => "{BasePlugin.associate_ext}",
104 'type' => "string",
105 'reqd' => "no" },
106 { 'name' => "associate_tail_re",
107 'desc' => "{BasePlugin.associate_tail_re}",
108 'type' => "string",
109 'reqd' => "no" },
110 { 'name' => "OIDtype",
111 'desc' => "{import.OIDtype}",
112 'type' => "enum",
113 'list' => $oidtype_list,
114 # leave default empty so we can tell if its been set or not - if not set will use option from import.pl
115 'deft' => "auto",
116 'reqd' => "no" },
117 { 'name' => "OIDmetadata",
118 'desc' => "{import.OIDmetadata}",
119 'type' => "metadata",
120 'deft' => "dc.Identifier",
121 'reqd' => "no" },
122# { 'name' => "use_as_doc_identifier",
123# 'desc' => "{BasePlugin.use_as_doc_identifier}",
124# 'type' => "string",
125# 'reqd' => "no" ,
126# 'deft' => "" } ,
127 { 'name' => "no_cover_image",
128 'desc' => "{BasePlugin.no_cover_image}",
129 'type' => "flag",
130 'reqd' => "no" },
131# { 'name' => "filename_encoding",
132# 'desc' => "{BasePlugin.filename_encoding}",
133# 'type' => "enum",
134# 'deft' => "auto",
135# 'list' => $encoding_plus_auto_list,
136# 'reqd' => "no" },
137 { 'name' => "smart_block",
138 'desc' => "{common.deprecated}. {BasePlugin.smart_block}",
139 'type' => "flag",
140 'reqd' => "no",
141 'hiddengli' => "yes" }, # deprecated, but leave in for old collections
142 { 'name' => "file_rename_method",
143 'desc' => "{BasePlugin.file_rename_method}",
144 'type' => "enum",
145 'deft' => &get_default_file_rename_method(), # by default rename imported files and assoc files using this encoding
146 'list' => $file_rename_method_list,
147 'reqd' => "no"
148 }
149
150 ];
151
152
153my $options = { 'name' => "BasePlugin",
154 'desc' => "{BasePlugin.desc}",
155 'abstract' => "yes",
156 'inherits' => "yes",
157 'args' => $arguments };
158
159sub new {
160
161 my ($class) = shift (@_);
162 my ($pluginlist,$inputargs,$hashArgOptLists,$auxiliary) = @_;
163 push(@$pluginlist, $class);
164
165 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
166 push(@{$hashArgOptLists->{"OptList"}},$options);
167
168 my $self = new EncodingUtil($pluginlist, $inputargs, $hashArgOptLists,$auxiliary);
169
170 if ($self->{'info_only'}) {
171 # don't worry about any options etc
172 return bless $self, $class;
173 }
174 if ($self->{'smart_block'}) {
175 print STDERR "WARNING: -smart_block option has been deprecated and is no longer useful\n";
176 }
177 $self->{'smart_block'} = undef;
178
179 my $plugin_name = (defined $pluginlist->[0]) ? $pluginlist->[0] : $class;
180 $self->{'plugin_type'} = $plugin_name;
181
182 # remove ex. from OIDmetadata iff it's the only namespace prefix
183 $self->{'OIDmetadata'} =~ s/^ex\.([^.]+)$/$1/ if defined $self->{'OIDmetadata'};
184 $self->{'num_processed'} = 0;
185 $self->{'num_not_processed'} = 0;
186 $self->{'num_blocked'} = 0;
187 $self->{'num_archives'} = 0;
188 $self->{'cover_image'} = 1; # cover image is on by default
189 $self->{'cover_image'} = 0 if ($self->{'no_cover_image'});
190 $self->{'can_process_directories'} = 0;
191 #$self->{'option_list'} = $hashArgOptLists->{"OptList"};
192
193 my $associate_ext = $self->{'associate_ext'};
194 if ((defined $associate_ext) && ($associate_ext ne "")) {
195
196 my $associate_tail_re = $self->{'associate_tail_re'};
197 if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
198 my $outhandle = $self->{'outhandle'};
199 print $outhandle "Warning: can only specify 'associate_ext' or 'associate_tail_re'\n";
200 print $outhandle " defaulting to 'associate_tail_re'\n";
201 }
202 else {
203 my @exts = split(/,/,$associate_ext);
204
205 my @exts_bracketed = map { $_ = "(?:\\.$_)" } @exts;
206 my $associate_tail_re = join("|",@exts_bracketed);
207 $self->{'associate_tail_re'} = $associate_tail_re;
208 }
209
210 delete $self->{'associate_ext'};
211 }
212
213 return bless $self, $class;
214
215}
216
217sub merge_inheritance
218{
219 my $self = {};
220 my @child_selfs = @_;
221
222 foreach my $child_self (@child_selfs) {
223 foreach my $key (keys %$child_self) {
224 if (defined $self->{$key}) {
225 if ($self->{$key} ne $child_self->{$key}) {
226# print STDERR "Warning: Conflicting value in multiple inheritance for '$key'\n";
227# print STDERR "Existing stored value = $self->{$key}\n";
228# print STDERR "New (child) value = $child_self->{$key}\n";
229# print STDERR "Keeping existing value\n";
230 # Existing value seems to be option specified in collect.cfg
231
232 ### $self->{$key} = $child_self->{$key};
233
234 }
235 else {
236## print STDERR "****Info: Value $self->{$key} for $key already defined through multiple inheritance as the same value\n";
237 }
238
239 }
240 else {
241 $self->{$key} = $child_self->{$key};
242 }
243 }
244 }
245
246 return $self;
247}
248
249# initialize BasePlugin options
250# if init() is overridden in a sub-class, remember to call BasePlugin::init()
251sub init {
252 my $self = shift (@_);
253 my ($verbosity, $outhandle, $failhandle) = @_;
254
255 $self->SUPER::init(@_);
256
257 # set process_exp and block_exp to defaults unless they were
258 # explicitly set
259
260 if ((!$self->is_recursive()) and
261 (!defined $self->{'process_exp'}) || ($self->{'process_exp'} eq "")) {
262
263 $self->{'process_exp'} = $self->get_default_process_exp ();
264 if ($self->{'process_exp'} eq "") {
265 warn ref($self) . " Warning: Non-recursive plugin has no process_exp\n";
266 }
267 }
268
269 if ((!defined $self->{'block_exp'}) || ($self->{'block_exp'} eq "")) {
270 $self->{'block_exp'} = $self->get_default_block_exp ();
271 }
272
273}
274
275sub begin {
276 my $self = shift (@_);
277 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
278
279 if ($self->{'OIDtype'} eq "auto") {
280 # hasn't been set in the plugin, use the processor values
281 $self->{'OIDtype'} = $processor->{'OIDtype'};
282 $self->{'OIDmetadata'} = $processor->{'OIDmetadata'};
283 }
284 if ($self->{'OIDtype'} eq "hash") {
285 # should we hash on the file or on the doc xml??
286 $self->{'OIDtype'} = $self->get_oid_hash_type();
287 if ($self->{'OIDtype'} !~ /^(hash_on_file|hash_on_ga_xml)$/) {
288 $self->{'OIDtype'} = "hash_on_file";
289 }
290 }
291}
292
293# This is called once if removeold is set with import.pl. Most plugins will do
294# nothing but if a plugin does any stuff outside of creating doc obj, then
295# it may need to clear something.
296sub remove_all {
297 my $self = shift (@_);
298 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
299}
300
301# This is called per document for docs that have been deleted from the
302# collection. Most plugins will do nothing
303# but if a plugin does any stuff outside of creating doc obj, then it may need
304# to clear something.
305sub remove_one {
306 my $self = shift (@_);
307
308 my ($file, $oids, $archivedir) = @_;
309 return 0 if $self->can_process_this_file($file);
310 return undef;
311}
312
313sub end {
314 # potentially called at the end of each plugin pass
315 # import.pl only has one plugin pass, but buildcol.pl has multiple ones
316
317 my ($self) = shift (@_);
318}
319
320sub deinit {
321 # called only once, after all plugin passes have been done
322
323 my ($self) = @_;
324}
325
326# default hashing type is to hash on the original file (or converted file)
327# override this to return hash_on_ga_xml for filetypes where hashing on the
328# file is no good eg video
329sub get_oid_hash_type {
330
331 my $self = shift (@_);
332
333 return "hash_on_file";
334}
335
336
337# this function should be overridden to return 1
338# in recursive plugins
339sub is_recursive {
340 my $self = shift (@_);
341
342 return 0;
343}
344
345sub get_default_block_exp {
346 my $self = shift (@_);
347
348 return "";
349}
350
351sub get_default_process_exp {
352 my $self = shift (@_);
353
354 return "";
355}
356
357
358# rename imported files and assoc files using URL encoding by default
359# as this will work for most plugins and give more legible filenames
360sub get_default_file_rename_method() {
361 my $self = shift (@_);
362 return "url";
363}
364
365# returns this plugin's active (possibly user-selected) file_rename_method
366sub get_file_rename_method() {
367 my $self = shift (@_);
368 my $rename_method = $self->{'file_rename_method'};
369 if($rename_method) {
370 return $rename_method;
371 } else {
372 return $self->get_default_file_rename_method();
373 }
374}
375
376# default implementation is to do nothing
377sub store_block_files {
378
379 my $self =shift (@_);
380 my ($filename_full_path, $block_hash) = @_;
381
382}
383
384# put files to block into hash
385sub use_block_expressions {
386
387 my $self =shift (@_);
388 my ($filename_full_path, $block_hash) = @_;
389
390 $filename_full_path = &util::upgrade_if_dos_filename($filename_full_path);
391
392 if ($self->{'block_exp'} ne "" && $filename_full_path =~ /$self->{'block_exp'}/) {
393 &util::block_filename($block_hash,$filename_full_path);
394 }
395
396}
397
398#default implementation is to block a file with same name as this, but extension jpg or JPG, if cover_images is on.
399sub block_cover_image
400{
401 my $self =shift;
402 my ($filename, $block_hash) = @_;
403
404 $filename = &util::upgrade_if_dos_filename($filename);
405
406 if ($self->{'cover_image'}) {
407 my $coverfile = $filename;
408 $coverfile =~ s/\.[^\\\/\.]+$/\.jpg/;
409
410 #if there is no file extension, coverfile will be the same as filename
411 return if $coverfile eq $filename;
412
413 if (!&FileUtils::fileExists($coverfile)) {
414 $coverfile =~ s/jpg$/JPG/;
415 }
416 if (&FileUtils::fileExists($coverfile)) {
417 &util::block_filename($block_hash,$coverfile);
418 }
419 }
420
421 return;
422}
423
424
425# discover all the files that should be blocked by this plugin
426# check the args ...
427sub file_block_read {
428
429 my $self = shift (@_);
430 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $gli) = @_;
431 # Keep track of filenames with same root but different extensions
432 # Used to support -associate_ext and the more generalised
433 # -associate_tail_re
434 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
435
436 if (!-d $filename_full_path) {
437 $block_hash->{'all_files'}->{$file} = 1;
438 }
439
440 my $associate_tail_re = $self->{'associate_tail_re'};
441 if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
442 my ($file_prefix,$file_ext)
443 = &util::get_prefix_and_tail_by_regex($filename_full_path,$associate_tail_re);
444 if ((defined $file_prefix) && (defined $file_ext)) {
445 my $shared_fileroot = $block_hash->{'shared_fileroot'};
446 if (!defined $shared_fileroot->{$file_prefix}) {
447 my $file_prefix_rec = { 'tie_to' => undef,
448 'exts' => {} };
449 $shared_fileroot->{$file_prefix} = $file_prefix_rec;
450 }
451
452 my $file_prefix_rec = $shared_fileroot->{$file_prefix};
453
454 if ($self->can_process_this_file($filename_full_path) && $file_ext !~ m/.\./) {
455 # This is the document the others should be tied to
456 $file_prefix_rec->{'tie_to'} = $file_ext;
457 }
458 else {
459 if ($file_ext =~ m/$associate_tail_re$/) {
460 # this file should be associated to the main one
461 $file_prefix_rec->{'exts'}->{$file_ext} = 1;
462 }
463 }
464
465 }
466 }
467
468 # check block expressions
469 $self->use_block_expressions($filename_full_path, $block_hash) unless $self->{'no_blocking'};
470
471 # now check whether we are actually processing this
472 if (!-f $filename_full_path || !$self->can_process_this_file($filename_full_path)) {
473 return undef; # can't recognise
474 }
475
476 # if we have a block_exp, then this overrides the normal 'smart' blocking
477 $self->store_block_files($filename_full_path, $block_hash) unless ($self->{'no_blocking'} || $self->{'block_exp'} ne "");
478
479 # block the cover image if there is one
480 if ($self->{'cover_image'}) {
481 $self->block_cover_image($filename_full_path, $block_hash);
482 }
483
484 return 1;
485}
486
487# plugins that rely on more than process_exp (eg XML plugins) can override this method
488sub can_process_this_file {
489 my $self = shift(@_);
490 my ($filename) = @_;
491
492 if (-d $filename && !$self->{'can_process_directories'}) {
493 return 0;
494 }
495
496 if ($self->{'process_exp'} ne "" && $filename =~ /$self->{'process_exp'}/) {
497 return 1;
498 }
499 return 0;
500
501}
502
503# Even if a plugin can extract metadata in its metadata_read pass,
504# make the default return 'undef' so processing of the file continues
505# down the pipeline, so other plugins can also have the opportunity to
506# locate metadata and set it up in the extrametakeys variables that
507# are passed around.
508
509sub can_process_this_file_for_metadata {
510 my $self = shift(@_);
511
512 return undef;
513}
514
515
516
517# Notionally written to be called once for each document, it is however safe to
518# call multiple times (as in the case of ImagePlugin) which calls this later on
519# after the original image has potentially been converted to a *new* source image
520# format (e.g. TIFF to PNG)
521
522sub set_Source_metadata {
523 my $self = shift (@_);
524 my ($doc_obj, $raw_filename, $filename_encoding, $section) = @_;
525
526 # 1. Sets the filename (Source) for display encoded as Unicode if possible,
527 # and (as a fallback) using %xx if not for non-ascii chars
528 # 2. Sets the url ref (SourceFile) to the URL encoded version
529 # of filename for generated files
530
531 my ($unused_full_rf, $raw_file) = &util::get_full_filenames("", $raw_filename);
532
533 my $this_section = (defined $section)? $section : $doc_obj->get_top_section();
534
535 my $octet_file = $raw_file;
536
537 # UTF-8 version of filename
538# if ((defined $ENV{"DEBUG_UNICODE"}) && ($ENV{"DEBUG_UNICODE"})) {
539# print STDERR "**** Setting Source Metadata given: $octet_file\n";
540# }
541
542 # Deal with (on Windows) raw filenames that are in their
543 # abbreviated DOS form
544
545 if (($ENV{'GSDLOS'} =~ m/^windows$/i) && ($^O ne "cygwin")) {
546 if ((defined $filename_encoding) && ($filename_encoding eq "unicode")) {
547 if (-e $raw_filename) {
548 my $unicode_filename = Win32::GetLongPathName($raw_filename);
549
550 my $unused_full_uf;
551 ($unused_full_uf, $octet_file) = &util::get_full_filenames("", $unicode_filename);
552 }
553 }
554 }
555
556 my $url_encoded_filename;
557 if ((defined $filename_encoding) && ($filename_encoding ne "ascii")) {
558 # => Generate a pretty print version of filename that is mapped to Unicode
559
560 # Use filename_encoding to map raw filename to a Perl unicode-aware string
561 $url_encoded_filename = decode($filename_encoding,$octet_file);
562 }
563 else {
564 # otherwise generate %xx encoded version of filename for char > 127
565 $url_encoded_filename = &unicode::raw_filename_to_url_encoded($octet_file);
566 }
567
568# if ((defined $ENV{"DEBUG_UNICODE"}) && ($ENV{"DEBUG_UNICODE"})) {
569# print STDERR "****** saving Source as: $url_encoded_filename\n";
570# }
571
572 # In the case of converted files and (generalized) exploded documents, there
573 # will already be a source filename => store as OrigSource before overriding
574 my $orig_source = $doc_obj->get_metadata_element ($this_section, "Source");
575 if ((defined $orig_source) && ($orig_source !~ m/^\s*$/)) {
576 $doc_obj->set_utf8_metadata_element($this_section, "OrigSource", $orig_source);
577 }
578
579 # Source is the UTF8 display name - not necessarily the name of the file on the system
580 if ($ENV{'GSDLOS'} =~ m/^darwin$/i) {
581 # on Darwin want all display strings to be in composed form, then can search on that
582 $url_encoded_filename = normalize('C', $url_encoded_filename); # Normalisation Form 'C' (composition)
583 }
584 # set_utf8_metadata actually sets perl unicode aware strings. not utf8
585 $doc_obj->set_utf8_metadata_element($this_section, "Source", $url_encoded_filename);
586
587
588 my $renamed_raw_file = &util::rename_file($raw_file, $self->{'file_rename_method'});
589 # If using URL encoding, then SourceFile is the url-reference to url-encoded
590 # renamed_raw_url: it's a url that refers to the actual file on the system
591 # this call just replaces % with %25
592 my $renamed_raw_url = &unicode::filename_to_url($renamed_raw_file);
593
594 $doc_obj->set_utf8_metadata_element($this_section, "SourceFile",
595 $renamed_raw_url);
596
597# if ((defined $ENV{"DEBUG_UNICODE"}) && ($ENV{"DEBUG_UNICODE"})) {
598# print STDERR "****** saving SourceFile as: $renamed_raw_url\n";
599# }
600}
601
602# this should be called by all plugins to set the oid of the doc obj, rather
603# than calling doc_obj->set_OID directly
604sub add_OID {
605 my $self = shift (@_);
606 my ($doc_obj, $force) = @_;
607
608 # don't add one if there is one already set, unless we are forced to do so
609 return unless ($doc_obj->get_OID() =~ /^NULL$/ || $force);
610 $doc_obj->set_OIDtype($self->{'OIDtype'}, $self->{'OIDmetadata'});
611
612 # see if there is a plugin specific set_OID function
613 if (defined ($self->can('set_OID'))) {
614 $self->set_OID(@_); # pass through doc_obj and any extra arguments
615 }
616 else {
617 # use the default set_OID() in doc.pm
618 $doc_obj->set_OID();
619 }
620
621}
622
623# The BasePlugin read_into_doc_obj() function. This function does all the
624# right things to make general options work for a given plugin. It doesn't do anything with the file other than setting reads in
625# a file and sets up a slew of metadata all saved in doc_obj, which
626# it then returns as part of a tuple (process_status,doc_obj)
627#
628# Much of this functionality used to reside in read, but it was broken
629# down into a supporting routine to make the code more flexible.
630#
631# recursive plugins (e.g. RecPlug) and specialized plugins like those
632# capable of processing many documents within a single file (e.g.
633# GMLPlug) will normally want to implement their own version of
634# read_into_doc_obj()
635#
636# Note that $base_dir might be "" and that $file might
637# include directories
638
639# currently blocking has been done before it gets here - does this affect secondary plugin stuff??
640sub read_into_doc_obj {
641 my $self = shift (@_);
642 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
643
644 my $outhandle = $self->{'outhandle'};
645
646 # should we move this to read? What about secondary plugins?
647 my $pp_file = &util::prettyprint_file($base_dir,$file,$gli);
648 print STDERR "<Processing n='$file' p='$self->{'plugin_type'}'>\n" if ($gli);
649 print $outhandle "$self->{'plugin_type'} processing $pp_file\n"
650 if $self->{'verbosity'} > 1;
651
652 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
653
654 # create a new document
655 my $doc_obj = new doc ($filename_full_path, "indexed_doc", $self->{'file_rename_method'});
656 my $top_section = $doc_obj->get_top_section();
657
658 $doc_obj->add_utf8_metadata($top_section, "Plugin", "$self->{'plugin_type'}");
659 $doc_obj->add_utf8_metadata($top_section, "FileSize", (-s $filename_full_path));
660
661
662 my $plugin_filename_encoding = $self->{'filename_encoding'};
663 my $filename_encoding = $self->deduce_filename_encoding($file,$metadata,$plugin_filename_encoding);
664 $self->set_Source_metadata($doc_obj,$filename_full_path,$filename_encoding,$top_section);
665
666 # plugin specific stuff - what args do we need here??
667 unless (defined ($self->process($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
668 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
669 return -1;
670 }
671
672 # include any metadata passed in from previous plugins
673 # note that this metadata is associated with the top level section
674 my $section = $doc_obj->get_top_section();
675 # can we merge these two methods??
676 $self->add_associated_files($doc_obj, $filename_full_path);
677 $self->extra_metadata ($doc_obj, $section, $metadata);
678 $self->auto_extract_metadata($doc_obj);
679
680 # if we haven't found any Title so far, assign one
681 # this was shifted to here from inside read()
682 $self->title_fallback($doc_obj,$section,$filename_no_path);
683
684 $self->add_OID($doc_obj);
685
686 $self->post_process_doc_obj($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli);
687 return (1,$doc_obj);
688}
689
690sub post_process_doc_obj {
691 my $self = shift (@_);
692 my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
693
694 return 1;
695}
696
697sub add_dummy_text {
698 my $self = shift(@_);
699 my ($doc_obj, $section) = @_;
700
701 # add NoText metadata so we can hide this dummy text in format statements
702 $doc_obj->add_metadata($section, "NoText", "1");
703
704 # lookup_string with extra '1' arg returns perl internal unicode aware text, so we use add_utf8_text so no encoding is done on it.
705 $doc_obj->add_utf8_text($section, &gsprintf::lookup_string("{BasePlugin.dummy_text}",1));
706 #$doc_obj->add_text($section, &gsprintf::lookup_string("{BasePlugin.dummy_text}",1));
707
708
709}
710
711# does nothing. Can be overridden by subclass
712sub auto_extract_metadata {
713 my $self = shift(@_);
714 my ($doc_obj) = @_;
715}
716
717# adds cover image, associate_file options stuff. Should be called by sub class
718# read_into_doc_obj
719sub add_associated_files {
720 my $self = shift(@_);
721 # whatis filename??
722 my ($doc_obj, $filename) = @_;
723
724 # add in the cover image
725 if ($self->{'cover_image'}) {
726 $self->associate_cover_image($doc_obj, $filename);
727 }
728 # store the original (used for eg TextPlugin to store the original for OAI)
729 if ($self->{'store_original_file'}) {
730 $self->associate_source_file($doc_obj, $filename);
731 }
732
733
734}
735
736# implement this if you are extracting metadata for other documents
737sub metadata_read {
738 my $self = shift (@_);
739 my ($pluginfo, $base_dir, $file, $block_hash,
740 $extrametakeys, $extrametadata, $extrametafile,
741 $processor, $gli, $aux) = @_;
742
743 # can we process this file??
744 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
745 return undef unless $self->can_process_this_file_for_metadata($filename_full_path);
746
747 return 1; # we recognise the file, but don't actually do anything with it
748}
749
750
751# The BasePlugin read() function. This function calls read_into_doc_obj()
752# to ensure all the right things to make general options work for a
753# given plugin are done. It then calls the process() function which
754# does all the work specific to a plugin (like the old read functions
755# used to do). Most plugins should define their own process() function
756# and let this read() function keep control.
757#
758# recursive plugins (e.g. RecPlug) and specialized plugins like those
759# capable of processing many documents within a single file (e.g.
760# GMLPlug) might want to implement their own version of read(), but
761# more likely need to implement their own version of read_into_doc_obj()
762#
763# Return number of files processed, undef if can't recognise, -1 if can't
764# process
765
766sub read {
767 my $self = shift (@_);
768 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
769
770 # can we process this file??
771 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
772
773 return undef unless $self->can_process_this_file($filename_full_path);
774
775 #print STDERR "**** BEFORE READ INTO DOC OBJ: $file\n";
776 my ($process_status,$doc_obj) = $self->read_into_doc_obj(@_);
777 #print STDERR "**** AFTER READ INTO DOC OBJ: $file\n";
778
779 if ((defined $process_status) && ($process_status == 1)) {
780
781 # process the document
782 $processor->process($doc_obj);
783
784 $self->{'num_processed'} ++;
785 undef $doc_obj;
786 }
787 # delete any temp files that we may have created
788 $self->clean_up_after_doc_obj_processing();
789
790
791 # if process_status == 1, then the file has been processed.
792 return $process_status;
793
794}
795
796# returns undef if file is rejected by the plugin
797sub process {
798 my $self = shift (@_);
799 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
800
801 gsprintf(STDERR, "BasePlugin::process {common.must_be_implemented}\n");
802
803 my ($cpackage,$cfilename,$cline,$csubr,$chas_args,$cwantarray) = caller(1);
804 print STDERR "Calling method: $cfilename:$cline $cpackage->$csubr\n";
805
806 die "\n";
807
808 return undef; # never gets here
809}
810
811# overwrite this method to delete any temp files that we have created
812sub clean_up_after_doc_obj_processing {
813 my $self = shift(@_);
814
815}
816
817
818
819sub filename_based_title
820{
821 my $self = shift (@_);
822 my ($file) = @_;
823
824 my $file_derived_title = $file;
825 $file_derived_title =~ s/_/ /g;
826 $file_derived_title =~ s/\.[^.]+$//;
827
828 return $file_derived_title;
829}
830
831
832sub title_fallback
833{
834 my $self = shift (@_);
835 my ($doc_obj,$section,$file) = @_;
836
837 if (!defined $doc_obj->get_metadata_element ($section, "Title")
838 || $doc_obj->get_metadata_element($section, "Title") eq "") {
839
840 my $source_file = $doc_obj->get_metadata_element($section, "Source");
841 my $file_derived_title;
842 if (defined $source_file) {
843 $file_derived_title = $self->filename_based_title($source_file);
844 }
845 else {
846 # pp = pretty print
847 my $pp_file = (defined $source_file) ? $source_file : $file;
848
849 my $raw_title = $self->filename_based_title($file);
850 my $file_derived_title = &unicode::raw_filename_to_url_encoded($raw_title);
851 }
852
853
854 if (!defined $doc_obj->get_metadata_element ($section, "Title")) {
855 $doc_obj->add_utf8_metadata ($section, "Title", $file_derived_title);
856 }
857 else {
858 $doc_obj->set_utf8_metadata_element ($section, "Title", $file_derived_title);
859 }
860 }
861
862}
863
864# add any extra metadata that's been passed around from one
865# plugin to another.
866# extra_metadata uses add_utf8_metadata so it expects metadata values
867# to already be in utf8
868sub extra_metadata {
869 my $self = shift (@_);
870 my ($doc_obj, $cursection, $metadata) = @_;
871
872 my $associate_tail_re = $self->{'associate_tail_re'};
873
874# Sort the extra metadata for diffcol so these meta appear in a consistent order
875# in doc.xml. Necessary for the ex.PDF.* and ex.File.* meta that's extracted in
876# the PDFBox collection, as the order of these varies between CentOS and Ubuntu.
877 foreach my $field (sort keys(%$metadata)) {
878# foreach my $field (keys(%$metadata)) {
879 # $metadata->{$field} may be an array reference
880 if ($field eq "gsdlassocfile_tobe") {
881 # 'gsdlassocfile_tobe' is artificially introduced metadata
882 # that is used to signal that certain additional files should
883 # be tied to this document. Useful in situations where a
884 # metadata pass in the plugin pipeline works out some files
885 # need to be associated with a document, but the document hasn't
886 # been formed yet.
887 my $equiv_form = "";
888 foreach my $gaf (@{$metadata->{$field}}) {
889 my ($full_filename,$mimetype) = ($gaf =~ m/^(.*):(.*):$/);
890 my ($tail_filename) = ($full_filename =~ /^.*[\/\\](.+?)$/);
891
892 # we need to make sure the filename is valid utf-8 - we do
893 # this by url or base64 encoding it
894 # $tail_filename is the name that we store the file as
895 $tail_filename = &util::rename_file($tail_filename, $self->{'file_rename_method'});
896 $doc_obj->associate_file($full_filename,$tail_filename,$mimetype);
897 $doc_obj->associate_source_file($full_filename);
898 # If the filename is url_encoded, we need to encode the % signs
899 # in the filename, so that it works in a url
900 my $url_tail_filename = &unicode::filename_to_url($tail_filename);
901 # work out extended tail extension (i.e. matching tail re)
902
903 my ($file_prefix,$file_extended_ext)
904 = &util::get_prefix_and_tail_by_regex($tail_filename,$associate_tail_re);
905 my ($pre_doc_ext) = ($file_extended_ext =~ m/^(.*)\..*$/);
906 my ($doc_ext) = ($tail_filename =~ m/^.*\.(.*)$/);
907
908 # the greenstone 2 stuff
909 my $start_doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/{Or}{[parent(Top):assocfilepath],[assocfilepath]}/$url_tail_filename\">";
910 #my $start_doclink = "<a href=\'_httpprefix_/collect/[collection]/index/assoc/[assocfilepath]/$url_tail_filename\'>";
911 my $start_doclink_gs3 = "<a href=\'_httpprefix_/collect/[collection]/index/assoc/[assocfilepath]/$url_tail_filename\'>";
912
913 my $srcicon = "_icon".$doc_ext."_";
914 my $end_doclink = "</a>";
915
916 my $assoc_form = "$start_doclink\{If\}{$srcicon,$srcicon,$doc_ext\}$end_doclink";
917
918
919 if (defined $pre_doc_ext && $pre_doc_ext ne "") {
920 # for metadata such as [mp3._edited] [mp3._full] ...
921 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.$pre_doc_ext", $assoc_form);
922 }
923
924 # for multiple metadata such as [mp3.assoclink]
925 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.assoclink", $assoc_form);
926
927 $equiv_form .= " $assoc_form";
928
929 # following are used for greenstone 3,
930 $doc_obj->add_utf8_metadata ($cursection, "equivDocLink", $start_doclink_gs3);
931 $doc_obj->add_utf8_metadata ($cursection, "equivDocIcon", $srcicon);
932 $doc_obj->add_utf8_metadata ($cursection, "/equivDocLink", $end_doclink);
933
934 }
935 $doc_obj->add_utf8_metadata ($cursection, "equivlink", $equiv_form);
936 }
937 elsif ($field eq "gsdlzipfilename") {
938 # special case for when files have come out of a zip. source_path
939 # (used for archives dbs and keeping track for incremental import)
940 # must be set to the zip file name
941 my $zip_filename = $metadata->{$field};
942 # overwrite the source_path
943 $doc_obj->set_source_path($zip_filename);
944 # and set the metadata
945 $zip_filename = &util::filename_within_collection($zip_filename);
946 $zip_filename = $doc_obj->encode_filename($zip_filename, $self->{'file_rename_method'});
947 $doc_obj->add_utf8_metadata ($cursection, $field, $zip_filename);
948 }
949 elsif (ref ($metadata->{$field}) eq "ARRAY") {
950 map {
951 $doc_obj->add_utf8_metadata ($cursection, $field, $_);
952 } @{$metadata->{$field}};
953 } else {
954 $doc_obj->add_utf8_metadata ($cursection, $field, $metadata->{$field});
955 }
956 }
957}
958
959
960sub compile_stats {
961 my $self = shift(@_);
962 my ($stats) = @_;
963
964 $stats->{'num_processed'} += $self->{'num_processed'};
965 $stats->{'num_not_processed'} += $self->{'num_not_processed'};
966 $stats->{'num_archives'} += $self->{'num_archives'};
967
968}
969sub associate_source_file {
970 my $self = shift(@_);
971
972 my ($doc_obj, $filename) = @_;
973 my $cursection = $doc_obj->get_top_section();
974 my $assocfilename = $doc_obj->get_assocfile_from_sourcefile();
975
976 $doc_obj->associate_file($filename, $assocfilename, undef, $cursection);
977 # srclink_file is now deprecated because of the "_" in the metadataname. Use srclinkFile
978 $doc_obj->add_utf8_metadata ($cursection, "srclink_file", $doc_obj->get_sourcefile());
979 $doc_obj->add_utf8_metadata ($cursection, "srclinkFile", $doc_obj->get_sourcefile());
980}
981
982sub associate_cover_image {
983 my $self = shift(@_);
984 my ($doc_obj, $filename) = @_;
985
986 my $upgraded_filename = &util::upgrade_if_dos_filename($filename);
987
988 $filename =~ s/\.[^\\\/\.]+$/\.jpg/;
989 $upgraded_filename =~ s/\.[^\\\/\.]+$/\.jpg/;
990
991 if (exists $self->{'covers_missing_cache'}->{$upgraded_filename}) {
992 # don't stat() for existence e.g. for multiple document input files
993 # (eg SplitPlug)
994 return;
995 }
996
997 my $top_section=$doc_obj->get_top_section();
998
999 if (&FileUtils::fileExists($upgraded_filename)) {
1000 $doc_obj->associate_source_file($filename);
1001 $doc_obj->associate_file($filename, "cover.jpg", "image/jpeg");
1002 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1003 } else {
1004 my $upper_filename = $filename;
1005 my $upgraded_upper_filename = $upgraded_filename;
1006
1007 $upper_filename =~ s/jpg$/JPG/;
1008 $upgraded_upper_filename =~ s/jpg$/JPG/;
1009
1010 if (&FileUtils::fileExists($upgraded_upper_filename)) {
1011 $doc_obj->associate_source_file($upper_filename);
1012 $doc_obj->associate_file($upper_filename, "cover.jpg",
1013 "image/jpeg");
1014 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1015 } else {
1016 # file doesn't exist, so record the fact that it's missing so
1017 # we don't stat() again (stat is slow)
1018 $self->{'covers_missing_cache'}->{$upgraded_filename} = 1;
1019 }
1020 }
1021
1022}
1023
1024
1025# Overridden by exploding plugins (eg. ISISPlug)
1026sub clean_up_after_exploding
1027{
1028 my $self = shift(@_);
1029}
1030
1031
1032
10331;
Note: See TracBrowser for help on using the repository browser.