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

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

blocking moved to EncodingUTil

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