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

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

made all plugins that implement read() call read_block to check process_exp, block_exp, smart blocking, cover image blocking etc

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