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

Last change on this file since 22663 was 22663, checked in by mdewsnip, 14 years ago

Changed "srclink_file" metadata to always contain the filename, instead of referencing another metadata element. This is so the C++ code can escape underscores in the filename values correctly.

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