source: trunk/gsdl/perllib/plugins/DBPlug.pm@ 7901

Last change on this file since 7901 was 7701, checked in by jrm21, 20 years ago

allow utf-8 as an alias for utf8

  • Property svn:keywords set to Author Date Id Revision
File size: 9.7 KB
Line 
1###########################################################################
2#
3# DBPlug.pm -- plugin to import records from a database
4#
5# A component of the Greenstone digital library software
6# from the New Zealand Digital Library Project at the
7# University of Waikato, New Zealand.
8#
9# Copyright (C) 2003 New Zealand Digital Library Project
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation; either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program; if not, write to the Free Software
23# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24#
25###########################################################################
26
27#
28# See <GSDLHOME>/etc/packages/example.dbi for an example config file!!
29#
30
31# Written by John McPherson for the NZDL project
32# Mar, Apr 2003
33
34package DBPlug;
35
36use strict;
37no strict 'refs'; # allow variable as a filehandle
38
39use BasPlug;
40use unicode;
41use parsargv;
42
43use DBI; # database independent stuff
44
45sub BEGIN {
46 @DBPlug::ISA = ('BasPlug');
47}
48
49my $arguments =
50 [ { 'name' => "process_exp",
51 'desc' => "{BasPlug.process_exp}",
52 'type' => "regexp",
53 'deft' => &get_default_process_exp(),
54 'reqd' => "no" }];
55
56my $options = { 'name' => "DBPlug",
57 'desc' => "{DBPlug.desc}",
58 'abstract' => "no",
59 'inherits' => "yes",
60 'args' => $arguments };
61
62sub new {
63 my ($class) = @_;
64 my $self = new BasPlug ($class, @_);
65 $self->{'plugin_type'} = "DBPlug";
66 my $option_list = $self->{'option_list'};
67 push( @{$option_list}, $options );
68
69 # no plugin-specific options
70# if (!parsargv::parse(\@_, "allow_extra_options")) {
71# $self->print_txt_usage(""); # Use default resource bundle
72# die "\n";
73# }
74
75
76 return bless $self, $class;
77}
78
79sub get_default_process_exp {
80 my $self = shift (@_);
81
82 return q^(?i)\.dbi$^;
83}
84# we don't have a per-greenstone document process() function!
85sub process {
86
87}
88
89
90sub read {
91 my $self = shift (@_);
92 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs) = @_;
93
94 # see if we can handle the passed file...
95 my $filename = $file;
96 $filename = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
97 if ($filename !~ /$self->{'process_exp'}/ || !-f $filename) {
98 # this plugin can't process this file type...
99 return undef;
100 }
101
102 my $outhandle = $self->{'outhandle'};
103 my $verbosity = $self->{'verbosity'};
104
105 print $outhandle "DBPlug: processing $file\n"
106 if $self->{'verbosity'} > 1;
107
108 # calculate the document hash, for document ids
109 my $hash="";
110
111 my $osexe = &util::get_os_exe();
112 my $hashfile_exe = &util::filename_cat($ENV{'GSDLHOME'},"bin",
113 $ENV{'GSDLOS'},"hashfile$osexe");
114 if (-e "$hashfile_exe") {
115 $hash = `hashfile$osexe \"$filename\"`;
116 $hash =~ /:\s*([0-9a-f]+)/i;
117 $hash="HASH$1";
118 }
119
120
121 # default options - may be overridden by config file
122 my $language=undef;
123 my $encoding=undef;
124 my $dbplug_debug=0;
125 my $username='';
126 my $password='';
127
128 # these settings must be set by the config file:
129 my $db=undef;
130
131# get id of pages from "nonempty", get latest version number from "recent", and
132# then get pagename from "page" and content from "version" !
133
134 my $sql_query = undef ;
135
136 my %db_to_greenstone_fields=();
137
138 # read in config file.
139 if (!open (CONF, $filename)) {
140 print $outhandle "DBPlug: can't read $filename: $!\n";
141 return 0;
142 }
143 my $line;
144 my $statement="";
145 my $callback="";
146 while (defined($line=<CONF>)) {
147 chomp $line;
148 $line =~ s/\s*#.*$//mg; # remove comments
149 $statement .= $line;
150 if ($statement =~ m/;\s*$/) { # ends with ";"
151 # check that it is safe
152 # assignment
153 if ($statement =~ m~\$(\w+)\s* = \s*
154 (\d # digits
155 | ".*?(?<!\\)" # " up to the next " not preceded by a \
156 | '.*?(?<!\\)' # ' up to the next ' not preceded by a \
157 )\s*;~x) { # /x means ignore comments and whitespace in rx
158 # evaluate the assignment
159 if (!eval "\$$1=$2;") {
160 my $err=$@;
161 chomp $err;
162 $err =~ s/\.$//; # remove a trailing .
163 print $outhandle "$err (in $filename)\n";
164 return 0; # there was an error reading the config file
165 }
166 } elsif ($callback) {
167 # add this line to the callback function
168 $callback .= $statement;
169 } elsif ($statement =~ /sub text_callback/) {
170 # this is the start of the callback function definition
171 $callback = $statement;
172 }
173 $statement = "";
174 } elsif ($statement =~ /\}\s*$/ && $callback) { # ends with {
175 $callback .= $statement ; $statement = "";
176 }
177 }
178 close CONF;
179 if ($callback) {
180 # try to check that the function is "safe"
181 if ($callback =~ /\b(?:system|open|pipe|readpipe|qx|kill|eval|do|use|require|exec|fork)\b/ ||
182 $callback =~ /[\`]|\|\-/) {
183 # no backticks or functions that start new processes allowed
184 print $outhandle "DBPlug: bad function in callback\n";
185 return 0;
186 }
187 }
188
189 if (!defined($db)) {
190 print $outhandle "DBPlug: error: $filename does not specify a db!\n";
191 return 0;
192 }
193 if (!defined($sql_query)) {
194 print $outhandle "DBPlug: error: no SQL query specified!\n";
195 return 0;
196 }
197 # connect to database
198 my $dbhandle=DBI->connect($db, $username, $password);
199
200 if (!defined($dbhandle)) {
201 die "DBPlug: could not connect to database, exiting.\n";
202 }
203 if (defined($dbplug_debug) && $dbplug_debug==1) {
204 print $outhandle "DBPlug (debug): connected ok\n";
205 }
206
207 my $statement_hand=$dbhandle->prepare($sql_query);
208 $statement_hand->execute;
209
210 # get the array-ref for the field names and cast it to array
211 my @field_names;
212 @field_names=@{ $statement_hand->{NAME} };
213
214 foreach my $fieldname (@field_names) {
215 if (defined($db_to_greenstone_fields{$fieldname})) {
216 if (defined($dbplug_debug) && $dbplug_debug==1) {
217 print $outhandle "DBPlug (debug): mapping db field "
218 . "'$fieldname' to "
219 . $db_to_greenstone_fields{$fieldname} . "\n";
220 }
221 $fieldname=$db_to_greenstone_fields{$fieldname};
222 }
223 }
224
225
226# print "DBPlug: names: " . join (", ", @field_names) . ".\n";
227 # get rows
228
229 my $count = 0;
230 my @row_array;
231
232 @row_array=$statement_hand->fetchrow_array; # fetchrow_hashref?
233
234 while (scalar(@row_array)) {
235 if (defined($dbplug_debug) && $dbplug_debug==1) {
236 print $outhandle "DBPlug (debug): retrieved a row from query\n";
237 }
238
239 # create a new document
240 my $doc_obj = new doc ($filename, "indexed_doc");
241 $doc_obj->set_OIDtype ($processor->{'OIDtype'});
242 my $cursection = $doc_obj->get_top_section();
243
244 # if $language not set in config file, will use BasPlug's default
245 if (defined($language)) {
246 $doc_obj->add_utf8_metadata($cursection, "Language", $language);
247 }
248 # if $encoding not set in config file, will use BasPlug's default
249 if (defined($encoding)) {
250 # allow some common aliases
251 if ($encoding =~ m/^utf[-_]8$/i) {$encoding="utf8"}
252 $encoding =~ s/-/_/g; # greenstone uses eg iso_8859_1
253 $doc_obj->add_utf8_metadata($cursection, "Encoding", $encoding);
254 }
255 $doc_obj->add_utf8_metadata($cursection,
256 "Source", &ghtml::dmsafe($db));
257 if ($self->{'cover_image'}) {
258 $self->associate_cover_image($doc_obj, $filename);
259 }
260 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
261
262
263 # include any metadata passed in from previous plugins
264 # note that this metadata is associated with the top level section
265 $self->extra_metadata ($doc_obj, $cursection,
266 $metadata);
267
268 # do any automatic metadata extraction
269 $self->auto_extract_metadata ($doc_obj);
270
271 my $unique_id=undef;
272
273 foreach my $fieldname (@field_names) {
274 my $fielddata=shift @row_array;
275 # use the specified encoding, defaulting to utf-8
276 if (defined($encoding) && $encoding ne "ascii"
277 && $encoding ne "utf8") {
278 $fielddata=&unicode::unicode2utf8(
279 &unicode::convert2unicode($encoding, \$fielddata)
280 );
281 }
282 if ($fieldname eq "text") {
283 # see if we have a text_callback() function defined
284 if (defined(&text_callback)) {
285 $fielddata=text_callback($fielddata);
286 }
287 # add as document text
288 $fielddata=~s@<@&lt;@g;
289 $fielddata=~s@>@&gt;@g; # for xml protection...
290 $fielddata=~s@_@\\_@g; # for macro language protection...
291 $doc_obj->add_utf8_text($cursection, $fielddata);
292 } elsif ($fieldname eq "Identifier") {
293 # use as greenstone's unique record id
294 if ($fielddata =~ /^\d+$/) {
295 # don't allow IDs that are completely numeric
296 $unique_id="id" . $fielddata;
297 } else {
298 $unique_id=$fielddata;
299 }
300 } else {
301 # add as document metadata
302 $fielddata=~s/\[/&#91;/g;
303 $fielddata=~s/\]/&#93;/g;
304 $doc_obj->add_utf8_metadata($cursection,
305 $fieldname, $fielddata);
306
307 }
308 }
309
310 if (!defined $unique_id) {
311 $doc_obj->set_OID($hash . "s$count");
312 } else {
313 # use our id from the database...
314 $doc_obj->set_OID($unique_id);
315 }
316
317
318 # process the document
319 $processor->process($doc_obj);
320
321
322 $count++;
323
324 # get next row
325 @row_array=$statement_hand->fetchrow_array; # fetchrow_hashref?
326 } # end of row_array is not empty
327
328 # check "$sth->err" if empty array for error
329 if ($statement_hand->err) {
330 print $outhandle "DBPlug: received error: \"" .
331 $statement_hand->errstr . "\"\n";
332 }
333
334 # clean up connection to database
335 $statement_hand->finish();
336 $dbhandle->disconnect();
337
338 # num of input files, rather than documents created?
339 $self->{'num_processed'}++;
340
341 return $count;
342}
343
3441;
Note: See TracBrowser for help on using the repository browser.