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

Last change on this file since 10434 was 10347, checked in by kjdon, 19 years ago

removed the unneeded 'use parsargv'

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