Removed perl warning
[koha.git] / C4 / Context.pm
1 # Copyright 2002 Katipo Communications
2 #
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA  02111-1307 USA
17
18 # $Id$
19
20 package C4::Context;
21 use strict;
22 use DBI;
23
24 use vars qw($VERSION $AUTOLOAD),
25         qw($context),
26         qw(@context_stack);
27
28 $VERSION = do { my @v = '$Revision$' =~ /\d+/g;
29                 shift(@v) . "." . join("_", map {sprintf "%03d", $_ } @v); };
30
31 =head1 NAME
32
33 C4::Context - Maintain and manipulate the context of a Koha script
34
35 =head1 SYNOPSIS
36
37   use C4::Context;
38
39   use C4::Context("/path/to/koha.conf");
40
41   $config_value = C4::Context->config("config_variable");
42   $db_handle = C4::Context->dbh;
43   $stopwordhash = C4::Context->stopwords;
44
45 =head1 DESCRIPTION
46
47 When a Koha script runs, it makes use of a certain number of things:
48 configuration settings in F</etc/koha.conf>, a connection to the Koha
49 database, and so forth. These things make up the I<context> in which
50 the script runs.
51
52 This module takes care of setting up the context for a script:
53 figuring out which configuration file to load, and loading it, opening
54 a connection to the right database, and so forth.
55
56 Most scripts will only use one context. They can simply have
57
58   use C4::Context;
59
60 at the top.
61
62 Other scripts may need to use several contexts. For instance, if a
63 library has two databases, one for a certain collection, and the other
64 for everything else, it might be necessary for a script to use two
65 different contexts to search both databases. Such scripts should use
66 the C<&set_context> and C<&restore_context> functions, below.
67
68 By default, C4::Context reads the configuration from
69 F</etc/koha.conf>. This may be overridden by setting the C<$KOHA_CONF>
70 environment variable to the pathname of a configuration file to use.
71
72 =head1 METHODS
73
74 =over 2
75
76 =cut
77 #'
78 # In addition to what is said in the POD above, a Context object is a
79 # reference-to-hash with the following fields:
80 #
81 # config
82 #       A reference-to-hash whose keys and values are the
83 #       configuration variables and values specified in the config
84 #       file (/etc/koha.conf).
85 # dbh
86 #       A handle to the appropriate database for this context.
87 # dbh_stack
88 #       Used by &set_dbh and &restore_dbh to hold other database
89 #       handles for this context.
90
91 use constant CONFIG_FNAME => "/etc/koha.conf";
92                                 # Default config file, if none is specified
93
94 $context = undef;               # Initially, no context is set
95 @context_stack = ();            # Initially, no saved contexts
96
97 # read_config_file
98 # Reads the specified Koha config file. Returns a reference-to-hash
99 # whose keys are the configuration variables, and whose values are the
100 # configuration values (duh).
101 # Returns undef in case of error.
102 sub read_config_file
103 {
104         my $fname = shift;      # Config file to read
105         my $retval = {};        # Return value: ref-to-hash holding the
106                                 # configuration
107
108         open (CONF, $fname) or return undef;
109
110         while (<CONF>)
111         {
112                 my $var;                # Variable name
113                 my $value;              # Variable value
114
115                 chomp;
116                 s/#.*//;                # Strip comments
117                 next if /^\s*$/;        # Ignore blank lines
118
119                 # Look for a line of the form
120                 #       var = value
121                 if (!/^\s*(\w+)\s*=\s*(.*?)\s*$/)
122                 {
123                         # FIXME - Complain about bogus line
124                         next;
125                 }
126
127                 # Found a variable assignment
128                 # FIXME - Ought to complain is this line sets a
129                 # variable that was already set.
130                 $var = $1;
131                 $value = $2;
132                 $retval->{$var} = $value;
133         }
134         close CONF;
135
136         return $retval;
137 }
138
139 sub import
140 {
141         my $package = shift;
142         my $conf_fname = shift;         # Config file name
143         my $context;
144
145         # Create a new context from the given config file name, if
146         # any, then set it as the current context.
147         $context = new C4::Context($conf_fname);
148         return undef if !defined($context);
149         $context->set_context;
150 }
151
152 =item new
153
154   $context = new C4::Context;
155   $context = new C4::Context("/path/to/koha.conf");
156
157 Allocates a new context. Initializes the context from the specified
158 file, which defaults to either the file given by the C<$KOHA_CONF>
159 environment variable, or F</etc/koha.conf>.
160
161 C<&new> does not set this context as the new default context; for
162 that, use C<&set_context>.
163
164 =cut
165 #'
166 sub new
167 {
168         my $class = shift;
169         my $conf_fname = shift;         # Config file to load
170         my $self = {};
171
172         # check that the specified config file exists
173         undef $conf_fname unless (defined $conf_fname && -e $conf_fname);
174         # Figure out a good config file to load if none was specified.
175         if (!defined($conf_fname))
176         {
177                 # If the $KOHA_CONF environment variable is set, use
178                 # that. Otherwise, use the built-in default.
179                 $conf_fname = $ENV{"KOHA_CONF"} ||
180                                 CONFIG_FNAME;
181         }
182         $self->{"config_file"} = $conf_fname;
183
184         # Load the desired config file.
185         $self->{"config"} = &read_config_file($conf_fname);
186         return undef if !defined($self->{"config"});
187
188         $self->{"dbh"} = undef;         # Database handle
189         $self->{"stopwords"} = undef; # stopwords list
190
191         bless $self, $class;
192         return $self;
193 }
194
195 =item set_context
196
197   $context = new C4::Context;
198   $context->set_context();
199 or
200   set_context C4::Context $context;
201
202   ...
203   restore_context C4::Context;
204
205 In some cases, it might be necessary for a script to use multiple
206 contexts. C<&set_context> saves the current context on a stack, then
207 sets the context to C<$context>, which will be used in future
208 operations. To restore the previous context, use C<&restore_context>.
209
210 =cut
211 #'
212 sub set_context
213 {
214         my $self = shift;
215         my $new_context;        # The context to set
216
217         # Figure out whether this is a class or instance method call.
218         #
219         # We're going to make the assumption that control got here
220         # through valid means, i.e., that the caller used an instance
221         # or class method call, and that control got here through the
222         # usual inheritance mechanisms. The caller can, of course,
223         # break this assumption by playing silly buggers, but that's
224         # harder to do than doing it properly, and harder to check
225         # for.
226         if (ref($self) eq "")
227         {
228                 # Class method. The new context is the next argument.
229                 $new_context = shift;
230         } else {
231                 # Instance method. The new context is $self.
232                 $new_context = $self;
233         }
234
235         # Save the old context, if any, on the stack
236         push @context_stack, $context if defined($context);
237
238         # Set the new context
239         $context = $new_context;
240 }
241
242 =item restore_context
243
244   &restore_context;
245
246 Restores the context set by C<&set_context>.
247
248 =cut
249 #'
250 sub restore_context
251 {
252         my $self = shift;
253
254         if ($#context_stack < 0)
255         {
256                 # Stack underflow.
257                 die "Context stack underflow";
258         }
259
260         # Pop the old context and set it.
261         $context = pop @context_stack;
262
263         # FIXME - Should this return something, like maybe the context
264         # that was current when this was called?
265 }
266
267 =item config
268
269   $value = C4::Context->config("config_variable");
270
271   $value = C4::Context->config_variable;
272
273 Returns the value of a variable specified in the configuration file
274 from which the current context was created.
275
276 The second form is more compact, but of course may conflict with
277 method names. If there is a configuration variable called "new", then
278 C<C4::Config-E<gt>new> will not return it.
279
280 =cut
281 #'
282 sub config
283 {
284         my $self = shift;
285         my $var = shift;                # The config variable to return
286
287         return undef if !defined($context->{"config"});
288                         # Presumably $self->{config} might be
289                         # undefined if the config file given to &new
290                         # didn't exist, and the caller didn't bother
291                         # to check the return value.
292
293         # Return the value of the requested config variable
294         return $context->{"config"}{$var};
295 }
296
297 =item preference
298
299   $sys_preference = C4::Context->preference("some_variable");
300
301 Looks up the value of the given system preference in the
302 systempreferences table of the Koha database, and returns it. If the
303 variable is not set, or in case of error, returns the undefined value.
304
305 =cut
306 #'
307 # FIXME - The preferences aren't likely to change over the lifetime of
308 # the script (and things might break if they did change), so perhaps
309 # this function should cache the results it finds.
310 sub preference
311 {
312         my $self = shift;
313         my $var = shift;                # The system preference to return
314         my $retval;                     # Return value
315         my $dbh = C4::Context->dbh;     # Database handle
316         my $sth;                        # Database query handle
317
318         # Look up systempreferences.variable==$var
319         $retval = $dbh->selectrow_array(<<EOT);
320                 SELECT  value
321                 FROM    systempreferences
322                 WHERE   variable='$var'
323                 LIMIT   1
324 EOT
325         return $retval;
326 }
327
328 # AUTOLOAD
329 # This implements C4::Config->foo, and simply returns
330 # C4::Context->config("foo"), as described in the documentation for
331 # &config, above.
332
333 # FIXME - Perhaps this should be extended to check &config first, and
334 # then &preference if that fails. OTOH, AUTOLOAD could lead to crappy
335 # code, so it'd probably be best to delete it altogether so as not to
336 # encourage people to use it.
337 sub AUTOLOAD
338 {
339         my $self = shift;
340
341         $AUTOLOAD =~ s/.*:://;          # Chop off the package name,
342                                         # leaving only the function name.
343         return $self->config($AUTOLOAD);
344 }
345
346 # _new_dbh
347 # Internal helper function (not a method!). This creates a new
348 # database connection from the data given in the current context, and
349 # returns it.
350 sub _new_dbh
351 {
352         my $db_driver = $context->{"config"}{"db_scheme"} || "mysql";
353                 # FIXME - It should be possible to use "MySQL" instead
354                 # of "mysql", "PostgreSQL" instead of "Pg", and so
355                 # forth.
356         my $db_name   = $context->{"config"}{"database"};
357         my $db_host   = $context->{"config"}{"hostname"};
358         my $db_user   = $context->{"config"}{"user"};
359         my $db_passwd = $context->{"config"}{"pass"};
360
361         return DBI->connect("DBI:$db_driver:$db_name:$db_host",
362                             $db_user, $db_passwd);
363 }
364
365 =item dbh
366
367   $dbh = C4::Context->dbh;
368
369 Returns a database handle connected to the Koha database for the
370 current context. If no connection has yet been made, this method
371 creates one, and connects to the database.
372
373 This database handle is cached for future use: if you call
374 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
375 times. If you need a second database handle, use C<&new_dbh> and
376 possibly C<&set_dbh>.
377
378 =cut
379 #'
380 sub dbh
381 {
382         my $self = shift;
383
384         # If there's already a database handle, return it.
385         return $context->{"dbh"} if defined($context->{"dbh"});
386
387         # No database handle yet. Create one.
388         $context->{"dbh"} = &_new_dbh();
389
390         return $context->{"dbh"};
391 }
392
393 =item new_dbh
394
395   $dbh = C4::Context->new_dbh;
396
397 Creates a new connection to the Koha database for the current context,
398 and returns the database handle (a C<DBI::db> object).
399
400 The handle is not saved anywhere: this method is strictly a
401 convenience function; the point is that it knows which database to
402 connect to so that the caller doesn't have to know.
403
404 =cut
405 #'
406 sub new_dbh
407 {
408         my $self = shift;
409
410         return &_new_dbh();
411 }
412
413 =item set_dbh
414
415   $my_dbh = C4::Connect->new_dbh;
416   C4::Connect->set_dbh($my_dbh);
417   ...
418   C4::Connect->restore_dbh;
419
420 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
421 C<&set_context> and C<&restore_context>.
422
423 C<&set_dbh> saves the current database handle on a stack, then sets
424 the current database handle to C<$my_dbh>.
425
426 C<$my_dbh> is assumed to be a good database handle.
427
428 =cut
429 #'
430 sub set_dbh
431 {
432         my $self = shift;
433         my $new_dbh = shift;
434
435         # Save the current database handle on the handle stack.
436         # We assume that $new_dbh is all good: if the caller wants to
437         # screw himself by passing an invalid handle, that's fine by
438         # us.
439         push @{$context->{"dbh_stack"}}, $context->{"dbh"};
440         $context->{"dbh"} = $new_dbh;
441 }
442
443 =item restore_dbh
444
445   C4::Context->restore_dbh;
446
447 Restores the database handle saved by an earlier call to
448 C<C4::Context-E<gt>set_dbh>.
449
450 =cut
451 #'
452 sub restore_dbh
453 {
454         my $self = shift;
455
456         if ($#{$context->{"dbh_stack"}} < 0)
457         {
458                 # Stack underflow
459                 die "DBH stack underflow";
460         }
461
462         # Pop the old database handle and set it.
463         $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
464
465         # FIXME - If it is determined that restore_context should
466         # return something, then this function should, too.
467 }
468
469 =item stopwords
470
471   $dbh = C4::Context->stopwords;
472
473 Returns a hash with stopwords.
474
475 This hash is cached for future use: if you call
476 C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
477
478 =cut
479 #'
480 sub stopwords
481 {
482         my $retval = {};
483
484         # If the hash already exists, return it.
485         return $context->{"stopwords"} if defined($context->{"stopwords"});
486
487         # No hash. Create one.
488         $context->{"stopwords"} = &_new_stopwords();
489
490         return $context->{"stopwords"};
491 }
492
493 # _new_stopwords
494 # Internal helper function (not a method!). This creates a new
495 # hash with stopwords
496 sub _new_stopwords
497 {
498         my $dbh = C4::Context->dbh;
499         my $stopwordlist;
500         my $sth = $dbh->prepare("select word from stopwords");
501         $sth->execute;
502         while (my $stopword = $sth->fetchrow_array) {
503                 my $retval = {};
504                 $stopwordlist->{$stopword} = uc($stopword);
505         }
506         return $stopwordlist;
507 }
508
509 1;
510 __END__
511
512 =back
513
514 =head1 ENVIRONMENT
515
516 =over 4
517
518 =item C<KOHA_CONF>
519
520 Specifies the configuration file to read.
521
522 =back
523
524 =head1 SEE ALSO
525
526 DBI(3)
527
528 =head1 AUTHOR
529
530 Andrew Arensburger <arensb at ooblick dot com>
531
532 =cut