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

Last change on this file since 12687 was 12687, checked in by kjdon, 18 years ago

moved 'use DBI' from the start to 'require DBI' in the read function - don't load it unless we have to. This way we can still run pluginfo.pl on DBPlug even if the module is not installed

  • Property svn:keywords set to Author Date Id Revision
File size: 11.1 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;
41
42#use DBI; # database independent stuff
43
44sub BEGIN {
45 @DBPlug::ISA = ('BasPlug');
46}
47
48my $arguments =
49 [ { 'name' => "process_exp",
50 'desc' => "{BasPlug.process_exp}",
51 'type' => "regexp",
52 'deft' => &get_default_process_exp(),
53 'reqd' => "no" }];
54
55my $options = { 'name' => "DBPlug",
56 'desc' => "{DBPlug.desc}",
57 'abstract' => "no",
58 'inherits' => "yes",
59 'args' => $arguments };
60
61sub new {
62 my ($class) = shift (@_);
63 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
64 push(@$pluginlist, $class);
65
66 if(defined $arguments){ push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});}
67 if(defined $options) { push(@{$hashArgOptLists->{"OptList"}},$options)};
68
69 my $self = new BasPlug($pluginlist, $inputargs, $hashArgOptLists);
70
71 return bless $self, $class;
72}
73
74sub get_default_process_exp {
75 my $self = shift (@_);
76
77 return q^(?i)\.dbi$^;
78}
79# we don't have a per-greenstone document process() function!
80sub process {
81
82}
83
84
85sub read {
86 my $self = shift (@_);
87 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
88
89
90 # see if we can handle the passed file...
91 my ($block_status,$filename) = $self->read_block(@_);
92 return $block_status if ((!defined $block_status) || ($block_status==0));
93
94 my $outhandle = $self->{'outhandle'};
95 my $verbosity = $self->{'verbosity'};
96
97 print $outhandle "DBPlug: processing $file\n"
98 if $self->{'verbosity'} > 1;
99 require DBI; # database independent stuff
100
101 # calculate the document hash, for document ids
102 my $hash="";
103
104 my $osexe = &util::get_os_exe();
105 my $hashfile_exe = &util::filename_cat($ENV{'GSDLHOME'},"bin",
106 $ENV{'GSDLOS'},"hashfile$osexe");
107 if (-e "$hashfile_exe") {
108 $hash = `hashfile$osexe \"$filename\"`;
109 $hash =~ /:\s*([0-9a-f]+)/i;
110 $hash="HASH$1";
111 }
112
113
114 # default options - may be overridden by config file
115 my $language=undef;
116 my $encoding=undef;
117 my $dbplug_debug=0;
118 my $username='';
119 my $password='';
120
121 # these settings must be set by the config file:
122 my $db=undef;
123
124# get id of pages from "nonempty", get latest version number from "recent", and
125# then get pagename from "page" and content from "version" !
126
127 my $sql_query_prime = undef ;
128 my $sql_query = undef ;
129
130 my %db_to_greenstone_fields=();
131 my %callbacks=();
132
133 # read in config file.
134 if (!open (CONF, $filename)) {
135 print $outhandle "DBPlug: can't read $filename: $!\n";
136 return 0;
137 }
138 my $line;
139 my $statement="";
140 my $callback="";
141 while (defined($line=<CONF>)) {
142 chomp $line;
143 $line .= " "; # for multi-line statements - don't conjoin!
144 $line =~ s/\s*\#.*$//mg; # remove comments
145 $statement .= $line;
146
147 if ($line =~ /^\}\s*$/ && $callback) { # ends the callback
148 $callback .= $statement ; $statement = "";
149 # try to check that the function is "safe"
150 if ($callback =~ /\b(?:system|open|pipe|readpipe|qx|kill|eval|do|use|require|exec|fork)\b/ ||
151 $callback =~ /[\`]|\|\-/) {
152 # no backticks or functions that start new processes allowed
153 print $outhandle "DBPlug: bad function in callback\n";
154 return 0;
155 }
156 $callback =~ s/sub (\w+?)_callback/sub/;
157 my $fieldname = $1;
158 my $ret = eval "\$callbacks{'$fieldname'} = $callback ; 1";
159 if (!defined($ret)) {
160 print $outhandle "DBPlug: error eval'ing callback: $@\n";
161 exit(1);
162 }
163 $callback="";
164 print $outhandle "DBPlug: callback registered for '$fieldname'\n"
165 if $dbplug_debug;
166 } elsif ($callback) {
167 # add this line to the callback function
168 $callback .= $statement;
169 $statement = "";
170 } elsif ($statement =~ m/;\s*$/) { # ends with ";"
171 # check that it is safe
172 # assignment
173 if ($statement =~ m~(\$\w+)\s* = \s*
174 (\d # digits
175 | ".*?(?<!\\)" # " up to the next " not preceded by a \
176 | '.*?(?<!\\)' # ' up to the next ' not preceded by a \
177 )\s*;~x || # /x means ignore comments and whitespace in rx
178 $statement =~ m~(\%\w+)\s*=\s*(\([\w\s\"\',:=>]+\))\s*;~ ) {
179 # evaluate the assignment, return 1 on success "
180 if (!eval "$1=$2; 1") {
181 my $err=$@;
182 chomp $err;
183 $err =~ s/\.$//; # remove a trailing .
184 print $outhandle "DBPlug: error evaluating `$statement'\n";
185 print $outhandle " $err (in $filename)\n";
186 return 0; # there was an error reading the config file
187 }
188 } elsif ($statement =~ /sub \w+_callback/) {
189 # this is the start of a callback function definition
190 $callback = $statement;
191 $statement = "";
192 } else {
193 print $outhandle "DBPlug: skipping statement `$statement'\n";
194 }
195 $statement = "";
196 }
197 }
198 close CONF;
199
200 if (!defined($db)) {
201 print $outhandle "DBPlug: error: $filename does not specify a db!\n";
202 return 0;
203 }
204 if (!defined($sql_query)) {
205 print $outhandle "DBPlug: error: no SQL query specified!\n";
206 return 0;
207 }
208 # connect to database
209 my $dbhandle=DBI->connect($db, $username, $password);
210
211 if (!defined($dbhandle)) {
212 die "DBPlug: could not connect to database, exiting.\n";
213 }
214 if (defined($dbplug_debug) && $dbplug_debug==1) {
215 print $outhandle "DBPlug (debug): connected ok\n";
216 }
217
218 my $statement_hand;
219
220 # The user gave 2 sql statements to execute?
221 if ($sql_query_prime) {
222 $statement_hand=$dbhandle->prepare($sql_query_prime);
223 $statement_hand->execute;
224 if ($statement_hand->err) {
225 print $outhandle "Error: " . $statement_hand->errstr . "\n";
226 return undef;
227 }
228 }
229
230 $statement_hand=$dbhandle->prepare($sql_query);
231 $statement_hand->execute;
232 if ($statement_hand->err) {
233 print $outhandle "Error: " . $statement_hand->errstr . "\n";
234 return undef;
235 }
236
237 # get the array-ref for the field names and cast it to array
238 my @field_names;
239 @field_names=@{ $statement_hand->{NAME} };
240
241 foreach my $fieldname (@field_names) {
242 if (defined($db_to_greenstone_fields{$fieldname})) {
243 if (defined($dbplug_debug) && $dbplug_debug==1) {
244 print $outhandle "DBPlug (debug): mapping db field "
245 . "'$fieldname' to "
246 . $db_to_greenstone_fields{$fieldname} . "\n";
247 }
248 $fieldname=$db_to_greenstone_fields{$fieldname};
249 }
250 }
251
252 # get rows
253
254 my $count = 0;
255 my @row_array;
256
257 @row_array=$statement_hand->fetchrow_array; # fetchrow_hashref?
258
259 while (scalar(@row_array)) {
260 if (defined($dbplug_debug) && $dbplug_debug==1) {
261 print $outhandle "DBPlug (debug): retrieved a row from query\n";
262 }
263
264 # create a new document
265 my $doc_obj = new doc ($filename, "indexed_doc");
266 $doc_obj->set_OIDtype ($processor->{'OIDtype'}, $processor->{'OIDmetadata'});
267 my $cursection = $doc_obj->get_top_section();
268
269 # if $language not set in config file, will use BasPlug's default
270 if (defined($language)) {
271 $doc_obj->add_utf8_metadata($cursection, "Language", $language);
272 }
273 # if $encoding not set in config file, will use BasPlug's default
274 if (defined($encoding)) {
275 # allow some common aliases
276 if ($encoding =~ m/^utf[-_]8$/i) {$encoding="utf8"}
277 $encoding =~ s/-/_/g; # greenstone uses eg iso_8859_1
278 $doc_obj->add_utf8_metadata($cursection, "Encoding", $encoding);
279 }
280 $doc_obj->add_utf8_metadata($cursection,
281 "Source", &ghtml::dmsafe($db));
282 if ($self->{'cover_image'}) {
283 $self->associate_cover_image($doc_obj, $filename);
284 }
285 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
286
287 $doc_obj->add_metadata($doc_obj->get_top_section(), "FileFormat", "DB");
288
289 # include any metadata passed in from previous plugins
290 # note that this metadata is associated with the top level section
291 $self->extra_metadata ($doc_obj, $cursection,
292 $metadata);
293
294 # do any automatic metadata extraction
295 $self->auto_extract_metadata ($doc_obj);
296
297 my $unique_id=undef;
298
299 foreach my $fieldname (@field_names) {
300 my $fielddata=shift @row_array;
301
302 if (! defined($fielddata) ) {
303 next; # this field was "" or NULL
304 }
305 # use the specified encoding, defaulting to utf-8
306 if (defined($encoding) && $encoding ne "ascii"
307 && $encoding ne "utf8") {
308 $fielddata=&unicode::unicode2utf8(
309 &unicode::convert2unicode($encoding, \$fielddata)
310 );
311 }
312 # see if we have a ****_callback() function defined
313 if (exists $callbacks{$fieldname}) {
314 my $funcptr = $callbacks{$fieldname};
315 $fielddata = &$funcptr($fielddata);
316 }
317
318 if ($fieldname eq "text") {
319 # add as document text
320 $fielddata=~s@<@&lt;@g;
321 $fielddata=~s@>@&gt;@g; # for xml protection...
322 $fielddata=~s@_@\\_@g; # for macro language protection...
323 $doc_obj->add_utf8_text($cursection, $fielddata);
324 } elsif ($fieldname eq "Identifier") {
325 # use as greenstone's unique record id
326 if ($fielddata =~ /^\d+$/) {
327 # don't allow IDs that are completely numeric
328 $unique_id="id" . $fielddata;
329 } else {
330 $unique_id=$fielddata;
331 }
332 } else {
333 # add as document metadata
334 $fielddata=~s/\[/&#91;/g;
335 $fielddata=~s/\]/&#93;/g;
336 $doc_obj->add_utf8_metadata($cursection,
337 $fieldname, $fielddata);
338
339 }
340 }
341
342 if (!defined $unique_id) {
343 $doc_obj->set_OID($hash . "s$count");
344 } else {
345 # use our id from the database...
346 $doc_obj->set_OID($unique_id);
347 }
348
349
350 # process the document
351 $processor->process($doc_obj);
352
353
354 $count++;
355
356 # get next row
357 @row_array=$statement_hand->fetchrow_array; # fetchrow_hashref?
358 } # end of row_array is not empty
359
360 # check "$sth->err" if empty array for error
361 if ($statement_hand->err) {
362 print $outhandle "DBPlug: received error: \"" .
363 $statement_hand->errstr . "\"\n";
364 }
365
366 # clean up connection to database
367 $statement_hand->finish();
368 $dbhandle->disconnect();
369
370 # num of input files, rather than documents created?
371 $self->{'num_processed'}++;
372
373 if (defined($dbplug_debug) && $dbplug_debug==1) {
374 print $outhandle "DBPlug: imported $count DB records as documents.\n";
375 }
376 $count;
377}
378
3791;
Note: See TracBrowser for help on using the repository browser.