source: gsdl/trunk/perllib/plugins/BasePlugin.pm@ 18404

Last change on this file since 18404 was 18404, checked in by ak19, 15 years ago
  1. BasePlugin's file_rename_method option changed from inherited to none; 2. unicode::filename_to_url subroutine no longer takes rename_method as a parameter (back to how it was before).
  • Property svn:keywords set to Author Date Id Revision
File size: 35.2 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;
33
34use encodings;
35use unicode;
36use textcat;
37use doc;
38use ghtml;
39use gsprintf 'gsprintf';
40
41use PrintInfo;
42
43BEGIN {
44 @BasePlugin::ISA = ( 'PrintInfo' );
45}
46
47# the different methods that can be applied when renaming
48# imported documents and their associated files
49our $file_rename_method_list =
50 [ { 'name' => "url",
51 'desc' => "{BasePlugin.rename_method.url}" },
52 { 'name' => "base64",
53 'desc' => "{BasePlugin.rename_method.base64}" },
54 { 'name' => "none",
55 'desc' => "{BasePlugin.rename_method.none}",
56 'hiddengli' => "yes" } ];
57
58our $encoding_list =
59 [ { 'name' => "ascii",
60 'desc' => "{BasePlugin.encoding.ascii}" },
61 { 'name' => "utf8",
62 'desc' => "{BasePlugin.encoding.utf8}" },
63 { 'name' => "unicode",
64 'desc' => "{BasePlugin.encoding.unicode}" } ];
65
66
67my $e = $encodings::encodings;
68foreach my $enc (sort {$e->{$a}->{'name'} cmp $e->{$b}->{'name'}} keys (%$e))
69{
70 my $hashEncode =
71 {'name' => $enc,
72 'desc' => $e->{$enc}->{'name'}};
73
74 push(@{$encoding_list},$hashEncode);
75}
76
77our $encoding_plus_auto_list =
78 [ { 'name' => "auto",
79 'desc' => "{BasePlugin.filename_encoding.auto}" },
80 { 'name' => "auto-language-analysis",
81 'desc' => "{BasePlugin.filename_encoding.auto_language_analysis}" }, # textcat
82 { 'name' => "auto-filesystem-encoding",
83 'desc' => "{BasePlugin.filename_encoding.auto_filesystem_encoding}" }, # locale
84 { 'name' => "auto-fl",
85 'desc' => "{BasePlugin.filename_encoding.auto_fl}" }, # locale followed by textcat
86 { 'name' => "auto-lf",
87 'desc' => "{BasePlugin.filename_encoding.auto_lf}" } ]; # texcat followed by locale
88
89push(@{$encoding_plus_auto_list},@{$encoding_list});
90
91our $oidtype_list =
92 [ { 'name' => "auto",
93 'desc' => "{BasePlugin.OIDtype.auto}" },
94 { 'name' => "hash",
95 'desc' => "{import.OIDtype.hash}" },
96 { 'name' => "assigned",
97 'desc' => "{import.OIDtype.assigned}" },
98 { 'name' => "incremental",
99 'desc' => "{import.OIDtype.incremental}" },
100 { 'name' => "dirname",
101 'desc' => "{import.OIDtype.dirname}" } ];
102
103my $arguments =
104 [ { 'name' => "process_exp",
105 'desc' => "{BasePlugin.process_exp}",
106 'type' => "regexp",
107 'deft' => "",
108 'reqd' => "no" },
109 { 'name' => "no_blocking",
110 'desc' => "{BasePlugin.no_blocking}",
111 'type' => "flag",
112 'reqd' => "no"},
113 { 'name' => "block_exp",
114 'desc' => "{BasePlugin.block_exp}",
115 'type' => "regexp",
116 'deft' => "",
117 'reqd' => "no" },
118 { 'name' => "associate_ext",
119 'desc' => "{BasePlugin.associate_ext}",
120 'type' => "string",
121 'reqd' => "no" },
122 { 'name' => "associate_tail_re",
123 'desc' => "{BasePlugin.associate_tail_re}",
124 'type' => "string",
125 'reqd' => "no" },
126 { 'name' => "OIDtype",
127 'desc' => "{import.OIDtype}",
128 'type' => "enum",
129 'list' => $oidtype_list,
130 # leave default empty so we can tell if its been set or not - if not set will use option from import.pl
131 'deft' => "auto",
132 'reqd' => "no",
133 'modegli' => "2" },
134 { 'name' => "OIDmetadata",
135 'desc' => "{import.OIDmetadata}",
136 'type' => "metadata",
137 'deft' => "dc.Identifier",
138 'reqd' => "no",
139 'modegli' => "2" },
140# { 'name' => "use_as_doc_identifier",
141# 'desc' => "{BasePlugin.use_as_doc_identifier}",
142# 'type' => "string",
143# 'reqd' => "no" ,
144# 'deft' => "" } ,
145 { 'name' => "no_cover_image",
146 'desc' => "{BasePlugin.no_cover_image}",
147 'type' => "flag",
148 'reqd' => "no" },
149 { 'name' => "filename_encoding",
150 'desc' => "{BasePlugin.filename_encoding}",
151 'type' => "enum",
152 'deft' => "auto",
153 'list' => $encoding_plus_auto_list,
154 'reqd' => "no" },
155 { 'name' => "smart_block",
156 'desc' => "{common.deprecated}. {BasePlugin.smart_block}",
157 'type' => "flag",
158 'reqd' => "no",
159 'hiddengli' => "yes" }, # deprecated, but leave in for old collections
160 { 'name' => "file_rename_method",
161 'desc' => "{BasePlugin.file_rename_method}",
162 'type' => "enum",
163 'deft' => &get_default_file_rename_method(), # by default rename imported files and assoc files using this encoding
164 'list' => $file_rename_method_list,
165 'reqd' => "no"
166 }
167
168 ];
169
170
171my $options = { 'name' => "BasePlugin",
172 'desc' => "{BasePlugin.desc}",
173 'abstract' => "yes",
174 'inherits' => "no",
175 'args' => $arguments };
176
177sub new {
178
179 my ($class) = shift (@_);
180 my ($pluginlist,$inputargs,$hashArgOptLists,$auxiliary) = @_;
181 push(@$pluginlist, $class);
182
183 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
184 push(@{$hashArgOptLists->{"OptList"}},$options);
185
186 my $self = new PrintInfo($pluginlist, $inputargs, $hashArgOptLists,$auxiliary);
187
188 if ($self->{'info_only'}) {
189 # don't worry about any options etc
190 return bless $self, $class;
191 }
192
193 if ($self->{'smart_block'}) {
194 print STDERR "WARNING: -smart_block option has been deprecated and is no longer useful\n";
195 }
196 $self->{'smart_block'} = undef;
197
198 my $plugin_name = (defined $pluginlist->[0]) ? $pluginlist->[0] : $class;
199 $self->{'plugin_type'} = $plugin_name;
200
201 $self->{'num_processed'} = 0;
202 $self->{'num_not_processed'} = 0;
203 $self->{'num_blocked'} = 0;
204 $self->{'num_archives'} = 0;
205 $self->{'cover_image'} = 1; # cover image is on by default
206 $self->{'cover_image'} = 0 if ($self->{'no_cover_image'});
207 #$self->{'option_list'} = $hashArgOptLists->{"OptList"};
208
209 my $associate_ext = $self->{'associate_ext'};
210 if ((defined $associate_ext) && ($associate_ext ne "")) {
211
212 my $associate_tail_re = $self->{'associate_tail_re'};
213 if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
214 my $outhandle = $self->{'outhandle'};
215 print $outhandle "Warning: can only specify 'associate_ext' or 'associate_tail_re'\n";
216 print $outhandle " defaulting to 'associate_tail_re'\n";
217 }
218 else {
219 my @exts = split(/,/,$associate_ext);
220
221 my @exts_bracketed = map { $_ = "(?:\\.$_)" } @exts;
222 my $associate_tail_re = join("|",@exts_bracketed);
223 $self->{'associate_tail_re'} = $associate_tail_re;
224 }
225
226 delete $self->{'associate_ext'};
227 }
228
229 return bless $self, $class;
230
231}
232
233sub merge_inheritance
234{
235 my $self = {};
236 my @child_selfs = @_;
237
238 foreach my $child_self (@child_selfs) {
239 foreach my $key (keys %$child_self) {
240 if (defined $self->{$key}) {
241 if ($self->{$key} ne $child_self->{$key}) {
242# print STDERR "Warning: Conflicting value in multiple inheritance for '$key'\n";
243# print STDERR "Existing stored value = $self->{$key}\n";
244# print STDERR "New (child) value = $child_self->{$key}\n";
245# print STDERR "Keeping existing value\n";
246 # Existing value seems to be option specified in collect.cfg
247
248 ### $self->{$key} = $child_self->{$key};
249
250 }
251 else {
252## print STDERR "****Info: Value $self->{$key} for $key already defined through multiple inheritance as the same value\n";
253 }
254
255 }
256 else {
257 $self->{$key} = $child_self->{$key};
258 }
259 }
260 }
261
262 return $self;
263}
264
265# initialize BasePlugin options
266# if init() is overridden in a sub-class, remember to call BasePlugin::init()
267sub init {
268 my $self = shift (@_);
269 my ($verbosity, $outhandle, $failhandle) = @_;
270
271 # verbosity is passed through from the processor
272 $self->{'verbosity'} = $verbosity;
273
274 # as are the outhandle and failhandle
275 $self->{'outhandle'} = $outhandle if defined $outhandle;
276 $self->{'failhandle'} = $failhandle;
277# $self->SUPER::init(@_);
278
279 # set process_exp and block_exp to defaults unless they were
280 # explicitly set
281
282 if ((!$self->is_recursive()) and
283 (!defined $self->{'process_exp'}) || ($self->{'process_exp'} eq "")) {
284
285 $self->{'process_exp'} = $self->get_default_process_exp ();
286 if ($self->{'process_exp'} eq "") {
287 warn ref($self) . " Warning: Non-recursive plugin has no process_exp\n";
288 }
289 }
290
291 if ((!defined $self->{'block_exp'}) || ($self->{'block_exp'} eq "")) {
292 $self->{'block_exp'} = $self->get_default_block_exp ();
293 }
294
295}
296
297sub begin {
298 my $self = shift (@_);
299 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
300
301 if ($self->{'OIDtype'} eq "auto") {
302 # hasn't been set in the plugin, use the processor values
303 $self->{'OIDtype'} = $processor->{'OIDtype'};
304 $self->{'OIDmetadata'} = $processor->{'OIDmetadata'};
305 }
306 if ($self->{'OIDtype'} eq "hash") {
307 # should we hash on the file or on the doc xml??
308 $self->{'OIDtype'} = $self->get_oid_hash_type();
309 if ($self->{'OIDtype'} !~ /^(hash_on_file|hash_on_ga_xml)$/) {
310 $self->{'OIDtype'} = "hash_on_file";
311 }
312 }
313}
314
315sub end {
316 # potentially called at the end of each plugin pass
317 # import.pl only has one plugin pass, but buildcol.pl has multiple ones
318
319 my ($self) = shift (@_);
320}
321
322sub deinit {
323 # called only once, after all plugin passes have been done
324
325 my ($self) = @_;
326}
327
328# default hashing type is to hash on the original file (or converted file)
329# override this to return hash_on_ga_xml for filetypes where hashing on the
330# file is no good eg video
331sub get_oid_hash_type {
332
333 my $self = shift (@_);
334
335 return "hash_on_file";
336}
337
338sub set_incremental {
339 my $self = shift(@_);
340 my ($incremental) = @_;
341
342 $self->{'incremental'} = $incremental;
343}
344
345# this function should be overridden to return 1
346# in recursive plugins
347sub is_recursive {
348 my $self = shift (@_);
349
350 return 0;
351}
352
353sub get_default_block_exp {
354 my $self = shift (@_);
355
356 return "";
357}
358
359sub get_default_process_exp {
360 my $self = shift (@_);
361
362 return "";
363}
364
365# rename imported files and assoc files using URL encoding by default
366# as this will work for most plugins and give more legible filenames
367sub get_default_file_rename_method() {
368 my $self = shift (@_);
369 return "url";
370}
371
372# returns this plugin's active (possibly user-selected) file_rename_method
373sub get_file_rename_method() {
374 my $self = shift (@_);
375 my $rename_method = $self->{'file_rename_method'};
376 if($rename_method) {
377 return $rename_method;
378 } else {
379 return $self->get_default_file_rename_method();
380 }
381}
382
383# default implementation is to do nothing
384sub store_block_files {
385
386 my $self =shift (@_);
387 my ($filename_full_path, $block_hash) = @_;
388
389}
390
391# put files to block into hash
392sub use_block_expressions {
393
394 my $self =shift (@_);
395 my ($filename_full_path, $block_hash) = @_;
396
397 if ($self->{'block_exp'} ne "" && $filename_full_path =~ /$self->{'block_exp'}/) {
398 $block_hash->{'file_blocks'}->{$filename_full_path} = 1;
399 }
400
401}
402
403#default implementation is to block a file with same name as this, but extension jpg or JPG, if cover_images is on.
404sub block_cover_image
405{
406 my $self =shift;
407 my ($filename, $block_hash) = @_;
408
409 if ($self->{'cover_image'}) {
410 my $coverfile = $filename;
411 $coverfile =~ s/\.[^\\\/\.]+$/\.jpg/;
412 if (!-e $coverfile) {
413 $coverfile =~ s/jpg$/JPG/;
414 }
415 if (-e $coverfile) {
416 $block_hash->{'file_blocks'}->{$coverfile} = 1;
417 }
418 }
419
420 return;
421}
422
423
424# discover all the files that should be blocked by this plugin
425# check the args ...
426sub file_block_read {
427
428 my $self = shift (@_);
429 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $gli) = @_;
430 # Keep track of filenames with same root but different extensions
431 # Used to support -associate_ext and the more generalised
432 # -associate_tail_re
433 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
434
435 my $associate_tail_re = $self->{'associate_tail_re'};
436 if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
437 my ($file_prefix,$file_ext)
438 = &util::get_prefix_and_tail_by_regex($filename_full_path,$associate_tail_re);
439 if ((defined $file_prefix) && (defined $file_ext)) {
440 my $shared_fileroot = $block_hash->{'shared_fileroot'};
441 if (!defined $shared_fileroot->{$file_prefix}) {
442 my $file_prefix_rec = { 'tie_to' => undef,
443 'exts' => {} };
444 $shared_fileroot->{$file_prefix} = $file_prefix_rec;
445 }
446
447 my $file_prefix_rec = $shared_fileroot->{$file_prefix};
448
449 if ($self->can_process_this_file($filename_full_path)) {
450 # This is the document the others should be tied to
451 $file_prefix_rec->{'tie_to'} = $file_ext;
452 }
453 else {
454 if ($file_ext =~ m/$associate_tail_re$/) {
455 # this file should be associated to the main one
456 $file_prefix_rec->{'exts'}->{$file_ext} = 1;
457 }
458 }
459
460 }
461 }
462
463 # check block expressions
464 $self->use_block_expressions($filename_full_path, $block_hash) unless $self->{'no_blocking'};
465
466 # now check whether we are actually processing this
467 if (!-f $filename_full_path || !$self->can_process_this_file($filename_full_path)) {
468 return undef; # can't recognise
469 }
470
471 # if we have a block_exp, then this overrides the normal 'smart' blocking
472 $self->store_block_files($filename_full_path, $block_hash) unless ($self->{'no_blocking'} || $self->{'block_exp'} ne "");
473
474 # block the cover image if there is one
475 if ($self->{'cover_image'}) {
476 $self->block_cover_image($filename_full_path, $block_hash);
477 }
478
479 return 1;
480}
481
482# plugins that rely on more than process_exp (eg XML plugins) can override this method
483sub can_process_this_file {
484 my $self = shift(@_);
485 my ($filename) = @_;
486
487 if ($self->{'process_exp'} ne "" && $filename =~ /$self->{'process_exp'}/) {
488 return 1;
489 }
490 return 0;
491
492}
493
494# just converts path as is to utf8.
495sub filepath_to_utf8 {
496 my $self = shift (@_);
497 my ($file, $file_encoding) = @_;
498 my $filemeta = $file;
499
500 my $filename_encoding = $self->{'filename_encoding'}; # filename encoding setting
501
502 # Whenever filename-encoding is set to any of the auto settings, we
503 # check if the filename is already in UTF8. If it is, then we're done.
504 if($filename_encoding =~ m/auto/) {
505 if(&unicode::check_is_utf8($filemeta))
506 {
507 $filename_encoding = "utf8";
508 return $filemeta;
509 }
510 }
511
512 # Auto setting, but filename is not utf8
513 if ($filename_encoding eq "auto")
514 {
515 # try textcat
516 $filename_encoding = $self->textcat_encoding($filemeta);
517
518 # check the locale next
519 $filename_encoding = $self->locale_encoding() if $filename_encoding eq "undefined";
520
521
522 # now try the encoding of the document, if available
523 if ($filename_encoding eq "undefined" && defined $file_encoding) {
524 $filename_encoding = $file_encoding;
525 }
526
527 }
528
529 elsif ($filename_encoding eq "auto-language-analysis")
530 {
531 $filename_encoding = $self->textcat_encoding($filemeta);
532
533 # now try the encoding of the document, if available
534 if ($filename_encoding eq "undefined" && defined $file_encoding) {
535 $filename_encoding = $file_encoding;
536 }
537 }
538
539 elsif ($filename_encoding eq "auto-filesystem-encoding")
540 {
541 # try locale
542 $filename_encoding = $self->locale_encoding();
543 }
544
545 elsif ($filename_encoding eq "auto-fl")
546 {
547 # filesystem-encoding (locale) then language-analysis (textcat)
548 $filename_encoding = $self->locale_encoding();
549
550 # try textcat
551 $filename_encoding = $self->textcat_encoding($filemeta) if $filename_encoding eq "undefined";
552
553 # else assume filename encoding is encoding of file content, if that's available
554 if ($filename_encoding eq "undefined" && defined $file_encoding) {
555 $filename_encoding = $file_encoding;
556 }
557 }
558
559 elsif ($filename_encoding eq "auto-lf")
560 {
561 # language-analysis (textcat) then filesystem-encoding (locale)
562 $filename_encoding = $self->textcat_encoding($filemeta);
563
564 # guess filename encoding from encoding of file content, if available
565 if ($filename_encoding eq "undefined" && defined $file_encoding) {
566 $filename_encoding = $file_encoding;
567 }
568
569 # try locale
570 $filename_encoding = $self->locale_encoding() if $filename_encoding eq "undefined";
571 }
572
573 # if still undefined, use utf8 as fallback
574 if ($filename_encoding eq "undefined") {
575 $filename_encoding = "utf8";
576 }
577
578 #print STDERR "**** UTF8 encoding the filename $filemeta ";
579
580 # if the filename encoding is set to utf8 but it isn't utf8 already--such as when
581 # 1. the utf8 fallback is used, or 2. if the system locale is used and happens to
582 # be always utf8 (in which case the filename's encoding is also set as utf8 even
583 # though the filename need not be if it originates from another system)--in such
584 # cases attempt to make the filename utf8 to match.
585 if($filename_encoding eq "utf8" && !&unicode::check_is_utf8($filemeta)) {
586 &unicode::ensure_utf8(\$filemeta);
587 }
588
589 # convert non-unicode encodings to utf8
590 if ($filename_encoding !~ m/(?:ascii|utf8|unicode)/) {
591 $filemeta = &unicode::unicode2utf8(
592 &unicode::convert2unicode($filename_encoding, \$filemeta)
593 );
594 }
595
596 #print STDERR " from encoding $filename_encoding -> $filemeta\n";
597 return $filemeta;
598}
599
600# gets the filename with no path, converts to utf8, and then dm safes it.
601# filename_encoding set by user
602sub filename_to_utf8_metadata
603{
604 my $self = shift (@_);
605 my ($file, $file_encoding) = @_;
606
607 my $outhandle = $self->{'outhandle'};
608
609 my ($filemeta) = $file =~ /([^\\\/]+)$/; # getting the tail of the filepath (skips all string parts containing slashes upto the end)
610 $filemeta = $self->filepath_to_utf8($filemeta, $file_encoding);
611
612 my $dmsafe_filemeta = &ghtml::dmsafe($filemeta);
613
614 return $dmsafe_filemeta;
615
616}
617
618sub locale_encoding {
619 my $self = shift(@_);
620
621 if (!defined $self->{'filesystem_encoding'}) {
622 $self->{'filesystem_encoding'} = $self->get_filesystem_encoding();
623 $self->{'filesystem_encoding'} = "undefined" if !defined $self->{'filesystem_encoding'};
624 }
625
626 #print STDERR "*** filename encoding determined based on locale: " . $self->{'filesystem_encoding'} . "\n";
627 return $self->{'filesystem_encoding'}; # can be the string "undefined"
628}
629
630sub textcat_encoding {
631 my $self = shift(@_);
632 my ($filemeta) = @_;
633
634 # analyse filenames without extensions and digits (and trimmed of surrounding
635 # whitespace), so that irrelevant chars don't confuse textcat
636 my $strictfilemeta = $filemeta;
637 $strictfilemeta =~ s/\.[^\.]+$//g;
638 $strictfilemeta =~ s/\d//g;
639 $strictfilemeta =~ s/^\s*//g;
640 $strictfilemeta =~ s/\s*$//g;
641
642 my $filename_encoding = $self->encoding_from_language_analysis($strictfilemeta);
643 if(!defined $filename_encoding) {
644 $filename_encoding = "undefined";
645 }
646
647 return $filename_encoding; # can be the string "undefined"
648}
649
650# performs textcat
651sub encoding_from_language_analysis {
652 my $self = shift(@_);
653 my ($text) = @_;
654
655 my $outhandle = $self->{'outhandle'};
656 my $best_encoding = undef;
657
658 # get the language/encoding of the textstring using textcat
659 $self->{'textcat'} = new textcat() unless defined($self->{'textcat'});
660 my $results = $self->{'textcat'}->classify_cached_filename(\$text);
661
662
663 if (scalar @$results < 0) {
664 return undef;
665 }
666
667 # We have some results, we choose the first
668 my ($language, $encoding) = $results->[0] =~ /^([^-]*)(?:-(.*))?$/;
669
670 $best_encoding = $encoding;
671 if (!defined $best_encoding) {
672 return undef;
673 }
674
675 if (defined $best_encoding && $best_encoding =~ m/^iso_8859/ && &unicode::check_is_utf8($text)) {
676 # the text is valid utf8, so assume that's the real encoding (since textcat is based on probabilities)
677 $best_encoding = 'utf8';
678 }
679
680
681 # check for equivalents where textcat doesn't have some encodings...
682 # eg MS versions of standard encodings
683 if (defined $best_encoding && $best_encoding =~ /^iso_8859_(\d+)/) {
684 my $iso = $1; # which variant of the iso standard?
685 # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
686 if ($text =~ /[\x80-\x9f]/) {
687 # Western Europe
688 if ($iso == 1 or $iso == 15) { $best_encoding = 'windows_1252' }
689 elsif ($iso == 2) {$best_encoding = 'windows_1250'} # Central Europe
690 elsif ($iso == 5) {$best_encoding = 'windows_1251'} # Cyrillic
691 elsif ($iso == 6) {$best_encoding = 'windows_1256'} # Arabic
692 elsif ($iso == 7) {$best_encoding = 'windows_1253'} # Greek
693 elsif ($iso == 8) {$best_encoding = 'windows_1255'} # Hebrew
694 elsif ($iso == 9) {$best_encoding = 'windows_1254'} # Turkish
695 }
696 }
697
698 if (defined $best_encoding && $best_encoding !~ /^(ascii|utf8|unicode)$/ &&
699 !defined $encodings::encodings->{$best_encoding})
700 {
701 if ($self->{'verbosity'}) {
702 gsprintf($outhandle, "BasePlugin: {ReadTextFile.unsupported_encoding}\n", $text, $best_encoding, "undef");
703 }
704 $best_encoding = undef;
705 }
706
707 return $best_encoding;
708}
709
710# uses locale
711sub get_filesystem_encoding {
712
713 my $self = shift(@_);
714
715 my $outhandle = $self->{'outhandle'};
716 my $filesystem_encoding = undef;
717
718 eval {
719 use POSIX qw(locale_h);
720
721 # With only one parameter, setlocale retrieves the
722 # current value
723 my $current_locale = setlocale(LC_CTYPE);
724
725 if ($current_locale =~ m/^.*\.(.*?)$/) {
726 my $char_encoding = lc($1);
727 if ($char_encoding =~ m/^(iso)(8859)(\d{1,2})$/) {
728 $char_encoding = "$1\_$2\_$3";
729 }
730
731 $char_encoding =~ s/-/_/g;
732 $char_encoding =~ s/^utf_8$/utf8/;
733
734 if ($char_encoding =~ m/^\d+$/) {
735 if (defined $encodings::encodings->{"windows_$char_encoding"}) {
736 $char_encoding = "windows_$char_encoding";
737 }
738 elsif (defined $encodings::encodings->{"dos_$char_encoding"}) {
739 $char_encoding = "dos_$char_encoding";
740 }
741 }
742
743 if (($char_encoding =~ m/(?:ascii|utf8|unicode)/)
744 || (defined $encodings::encodings->{$char_encoding})) {
745 $filesystem_encoding = $char_encoding;
746 }
747 else {
748 print $outhandle "Warning: Unsupported character encoding '$char_encoding' from locale '$current_locale'\n";
749 }
750 }
751
752
753 };
754 if ($@) {
755 print $outhandle "$@\n";
756 print $outhandle "Warning: Unable to establish locale. Will assume filesystem is UTF-8\n";
757
758 }
759 return $filesystem_encoding;
760}
761
762# is there ever only one Source? Sometimes this will be called twice, for images etc that are converted.
763sub set_Source_metadata {
764 my $self = shift (@_);
765 my ($doc_obj, $filename_no_path, $file_encoding) = @_;
766
767 my $top_section = $doc_obj->get_top_section();
768
769 # UTF-8 version of filename
770 my $filemeta = $self->filename_to_utf8_metadata($filename_no_path, $file_encoding);
771
772 # Source is the UTF8 display name - not necessarily the name of the file on the system
773 $doc_obj->set_utf8_metadata_element($top_section, "Source", $filemeta);
774
775 $filemeta = &util::rename_file($filemeta, $self->{'file_rename_method'});
776 # If using URL encoding, then SourceFile is the url-reference to url-encoded
777 # filemeta: it's a url that refers to the actual file on the system
778 $filemeta = &unicode::filename_to_url($filemeta);
779
780 $doc_obj->set_utf8_metadata_element($top_section, "SourceFile", $filemeta);
781}
782
783# this should be called by all plugins to set the oid of the doc obj, rather
784# than calling doc_obj->set_OID directly
785sub add_OID {
786 my $self = shift (@_);
787 my ($doc_obj) = @_;
788
789 $doc_obj->set_OIDtype($self->{'OIDtype'}, $self->{'OIDmetadata'});
790
791 # see if there is a plugin specific set_OID function
792 if (defined ($self->can('set_OID'))) {
793 $self->set_OID(@_); # pass through doc_obj and any extra arguments
794 }
795 else {
796 # use the default set_OID() in doc.pm
797 $doc_obj->set_OID();
798 }
799
800}
801
802# The BasePlugin read_into_doc_obj() function. This function does all the
803# right things to make general options work for a given plugin. It doesn't do anything with the file other than setting reads in
804# a file and sets up a slew of metadata all saved in doc_obj, which
805# it then returns as part of a tuple (process_status,doc_obj)
806#
807# Much of this functionality used to reside in read, but it was broken
808# down into a supporting routine to make the code more flexible.
809#
810# recursive plugins (e.g. RecPlug) and specialized plugins like those
811# capable of processing many documents within a single file (e.g.
812# GMLPlug) will normally want to implement their own version of
813# read_into_doc_obj()
814#
815# Note that $base_dir might be "" and that $file might
816# include directories
817
818# currently blocking has been done before it gets here - does this affect secondary plugin stuff??
819sub read_into_doc_obj {
820 my $self = shift (@_);
821 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
822
823 my $outhandle = $self->{'outhandle'};
824
825 # should we move this to read? What about secondary plugins?
826 print STDERR "<Processing n='$file' p='$self->{'plugin_type'}'>\n" if ($gli);
827 print $outhandle "$self->{'plugin_type'} processing $file\n"
828 if $self->{'verbosity'} > 1;
829
830 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
831 # create a new document
832 my $doc_obj = new doc ($filename_full_path, "indexed_doc", $self->{'file_rename_method'});
833 my $top_section = $doc_obj->get_top_section();
834
835 $doc_obj->add_utf8_metadata($top_section, "Plugin", "$self->{'plugin_type'}");
836 $doc_obj->add_utf8_metadata($top_section, "FileSize", (-s $filename_full_path));
837
838 # sets the UTF8 filename (Source) for display and sets the url ref to URL encoded version
839 # of the UTF8 filename (SourceFile) for generated files
840 $self->set_Source_metadata($doc_obj, $filename_no_path);
841
842 # plugin specific stuff - what args do we need here??
843 unless (defined ($self->process($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
844 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
845 return -1;
846 }
847
848 # include any metadata passed in from previous plugins
849 # note that this metadata is associated with the top level section
850 my $section = $doc_obj->get_top_section();
851 # can we merge these two methods??
852 $self->add_associated_files($doc_obj, $filename_full_path);
853 $self->extra_metadata ($doc_obj, $section, $metadata);
854 $self->auto_extract_metadata($doc_obj);
855
856 # if we haven't found any Title so far, assign one
857 # this was shifted to here from inside read()
858 $self->title_fallback($doc_obj,$section,$filename_no_path);
859
860 $self->add_OID($doc_obj);
861
862 return (1,$doc_obj);
863}
864
865sub add_dummy_text {
866 my $self = shift(@_);
867 my ($doc_obj, $section) = @_;
868
869 # add NoText metadata so we can hide this dummy text in format statements
870 $doc_obj->add_metadata($section, "NoText", "1");
871 $doc_obj->add_text($section, &gsprintf::lookup_string("{BasePlugin.dummy_text}",1));
872
873}
874
875# does nothing. Can be overridden by subclass
876sub auto_extract_metadata {
877 my $self = shift(@_);
878 my ($doc_obj) = @_;
879}
880
881# adds cover image, associate_file options stuff. Should be called by sub class
882# read_into_doc_obj
883sub add_associated_files {
884 my $self = shift(@_);
885 # whatis filename??
886 my ($doc_obj, $filename) = @_;
887
888 # add in the cover image
889 if ($self->{'cover_image'}) {
890 $self->associate_cover_image($doc_obj, $filename);
891 }
892
893
894}
895
896# implement this if you are extracting metadata for other documents
897sub metadata_read {
898 my $self = shift (@_);
899 my ($pluginfo, $base_dir, $file, $block_hash, $extrametakeys, $extrametadata, $processor, $maxdocs, $gli) = @_;
900
901 # can we process this file??
902 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
903 return undef unless $self->can_process_this_file($filename_full_path);
904
905 return 1; # we recognise the file, but don't actually do anything with it
906}
907
908
909# The BasePlugin read() function. This function calls read_into_doc_obj()
910# to ensure all the right things to make general options work for a
911# given plugin are done. It then calls the process() function which
912# does all the work specific to a plugin (like the old read functions
913# used to do). Most plugins should define their own process() function
914# and let this read() function keep control.
915#
916# recursive plugins (e.g. RecPlug) and specialized plugins like those
917# capable of processing many documents within a single file (e.g.
918# GMLPlug) might want to implement their own version of read(), but
919# more likely need to implement their own version of read_into_doc_obj()
920#
921# Return number of files processed, undef if can't recognise, -1 if can't
922# process
923
924sub read {
925 my $self = shift (@_);
926 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
927
928 # can we process this file??
929 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
930 return undef unless $self->can_process_this_file($filename_full_path);
931
932 my ($process_status,$doc_obj) = $self->read_into_doc_obj(@_);
933
934 if ((defined $process_status) && ($process_status == 1)) {
935
936 # process the document
937 $processor->process($doc_obj);
938
939 $self->{'num_processed'} ++;
940 undef $doc_obj;
941 }
942 # delete any temp files that we may have created
943 $self->clean_up_after_doc_obj_processing();
944
945 # if process_status == 1, then the file has been processed.
946 return $process_status;
947
948}
949
950# returns undef if file is rejected by the plugin
951sub process {
952 my $self = shift (@_);
953 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
954
955 gsprintf(STDERR, "BasePlugin::process {common.must_be_implemented}\n") && die "\n";
956
957 return undef; # never gets here
958}
959
960# overwrite this method to delete any temp files that we have created
961sub clean_up_after_doc_obj_processing {
962 my $self = shift(@_);
963
964}
965
966# write_file -- used by ConvertToPlug, for example in post processing
967#
968# where should this go, is here the best place??
969sub utf8_write_file {
970 my $self = shift (@_);
971 my ($textref, $filename) = @_;
972
973 if (!open (FILE, ">$filename")) {
974 gsprintf(STDERR, "ConvertToPlug::write_file {ConvertToPlug.could_not_open_for_writing} ($!)\n", $filename);
975 die "\n";
976 }
977 print FILE $$textref;
978
979 close FILE;
980}
981
982
983sub filename_based_title
984{
985 my $self = shift (@_);
986 my ($file) = @_;
987
988 my $file_derived_title = $file;
989 $file_derived_title =~ s/_/ /g;
990 $file_derived_title =~ s/\..*?$//;
991
992 return $file_derived_title;
993}
994
995
996sub title_fallback
997{
998 my $self = shift (@_);
999 my ($doc_obj,$section,$file) = @_;
1000
1001 if (!defined $doc_obj->get_metadata_element ($section, "Title") or $doc_obj->get_metadata_element($section, "Title") eq "") {
1002
1003 my $file_derived_title = $self->filename_to_utf8_metadata($self->filename_based_title($file));
1004 if (!defined $doc_obj->get_metadata_element ($section, "Title")) {
1005 $doc_obj->add_utf8_metadata ($section, "Title", $file_derived_title);
1006 }
1007 else {
1008 $doc_obj->set_utf8_metadata_element ($section, "Title", $file_derived_title);
1009 }
1010 }
1011
1012}
1013
1014# add any extra metadata that's been passed around from one
1015# plugin to another.
1016# extra_metadata uses add_utf8_metadata so it expects metadata values
1017# to already be in utf8
1018sub extra_metadata {
1019 my $self = shift (@_);
1020 my ($doc_obj, $cursection, $metadata) = @_;
1021
1022 my $associate_tail_re = $self->{'associate_tail_re'};
1023
1024 foreach my $field (keys(%$metadata)) {
1025 # $metadata->{$field} may be an array reference
1026 if ($field eq "gsdlassocfile_tobe") {
1027 # 'gsdlassocfile_tobe' is artificially introduced metadata
1028 # that is used to signal that certain additional files should
1029 # be tied to this document. Useful in situations where a
1030 # metadata pass in the plugin pipeline works out some files
1031 # need to be associated with a document, but the document hasn't
1032 # been formed yet.
1033 my $equiv_form = "";
1034 foreach my $gaf (@{$metadata->{$field}}) {
1035 my ($full_filename,$mimetype) = ($gaf =~ m/^(.*):(.*):$/);
1036 my ($tail_filename) = ($full_filename =~ /^.*[\/\\](.+?)$/);
1037
1038 # we need to make sure the filename is valid utf-8 - we do
1039 # this by url or base64 encoding it
1040 # $tail_filename is the name that we store the file as
1041 $tail_filename = &util::rename_file($tail_filename, $self->{'file_rename_method'});
1042 $doc_obj->associate_file($full_filename,$tail_filename,$mimetype);
1043 # If the filename is url_encoded, we need to encode the % signs
1044 # in the filename, so that it works in a url
1045 my $url_tail_filename = &unicode::filename_to_url($tail_filename);
1046 # work out extended tail extension (i.e. matching tail re)
1047
1048 my ($file_prefix,$file_extended_ext)
1049 = &util::get_prefix_and_tail_by_regex($tail_filename,$associate_tail_re);
1050 my ($pre_doc_ext) = ($file_extended_ext =~ m/^(.*)\..*$/);
1051 my ($doc_ext) = ($tail_filename =~ m/^.*\.(.*)$/);
1052 my $start_doclink = "<a href=\"_httpprefix_/collect/[collection]/index/assoc/{Or}{[parent(Top):archivedir],[archivedir]}/$url_tail_filename\">";
1053 my $srcicon = "_icon".$doc_ext."_";
1054 my $end_doclink = "</a>";
1055
1056 my $assoc_form = "$start_doclink\{If\}{$srcicon,$srcicon,$doc_ext\}$end_doclink";
1057
1058 if (defined $pre_doc_ext && $pre_doc_ext ne "") {
1059 # for metadata such as [mp3._edited] [mp3._full] ...
1060 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.$pre_doc_ext", $assoc_form);
1061 }
1062
1063 # for multiple metadata such as [mp3.assoclink]
1064 $doc_obj->add_utf8_metadata ($cursection, "$doc_ext.assoclink", $assoc_form);
1065
1066 $equiv_form .= " $assoc_form";
1067 }
1068 $doc_obj->add_utf8_metadata ($cursection, "equivlink", $equiv_form);
1069 }
1070 elsif (ref ($metadata->{$field}) eq "ARRAY") {
1071 map {
1072 $doc_obj->add_utf8_metadata ($cursection, $field, $_);
1073 } @{$metadata->{$field}};
1074 } else {
1075 $doc_obj->add_utf8_metadata ($cursection, $field, $metadata->{$field});
1076 }
1077 }
1078}
1079
1080
1081sub compile_stats {
1082 my $self = shift(@_);
1083 my ($stats) = @_;
1084
1085 $stats->{'num_processed'} += $self->{'num_processed'};
1086 $stats->{'num_not_processed'} += $self->{'num_not_processed'};
1087 $stats->{'num_archives'} += $self->{'num_archives'};
1088
1089}
1090
1091sub associate_cover_image {
1092 my $self = shift;
1093 my ($doc_obj, $filename) = @_;
1094
1095 $filename =~ s/\.[^\\\/\.]+$/\.jpg/;
1096 if (exists $self->{'covers_missing_cache'}->{$filename}) {
1097 # don't stat() for existence eg for multiple document input files
1098 # (eg SplitPlug)
1099 return;
1100 }
1101
1102 my $top_section=$doc_obj->get_top_section();
1103
1104 if (-e $filename) {
1105 $doc_obj->associate_file($filename, "cover.jpg", "image/jpeg");
1106 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1107 } else {
1108 my $upper_filename = $filename;
1109 $upper_filename =~ s/jpg$/JPG/;
1110 if (-e $upper_filename) {
1111 $doc_obj->associate_file($upper_filename, "cover.jpg",
1112 "image/jpeg");
1113 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1114 } else {
1115 # file doesn't exist, so record the fact that it's missing so
1116 # we don't stat() again (stat is slow)
1117 $self->{'covers_missing_cache'}->{$filename} = 1;
1118 }
1119 }
1120
1121}
1122
1123
1124# Overridden by exploding plugins (eg. ISISPlug)
1125sub clean_up_after_exploding
1126{
1127 my $self = shift(@_);
1128}
1129
1130
1131
11321;
Note: See TracBrowser for help on using the repository browser.