Cleaned things up a bit.
[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         # Figure out a good config file to load if none was specified.
173         if (!defined($conf_fname))
174         {
175                 # If the $KOHA_CONF environment variable is set, use
176                 # that. Otherwise, use the built-in default.
177                 $conf_fname = $ENV{"KOHA_CONF"} ||
178                                 CONFIG_FNAME;
179         }
180
181         $self->{"config_file"} = $conf_fname;
182
183         # Load the desired config file.
184         $self->{"config"} = &read_config_file($conf_fname);
185         return undef if !defined($self->{"config"});
186
187         $self->{"dbh"} = undef;         # Database handle
188         $self->{"stopwords"} = undef; # stopwords list
189
190         bless $self, $class;
191         return $self;
192 }
193
194 =item set_context
195
196   $context = new C4::Context;
197   $context->set_context();
198 or
199   set_context C4::Context $context;
200
201   ...
202   restore_context C4::Context;
203
204 In some cases, it might be necessary for a script to use multiple
205 contexts. C<&set_context> saves the current context on a stack, then
206 sets the context to C<$context>, which will be used in future
207 operations. To restore the previous context, use C<&restore_context>.
208
209 =cut
210 #'
211 sub set_context
212 {
213         my $self = shift;
214         my $new_context;        # The context to set
215
216         # Figure out whether this is a class or instance method call.
217         #
218         # We're going to make the assumption that control got here
219         # through valid means, i.e., that the caller used an instance
220         # or class method call, and that control got here through the
221         # usual inheritance mechanisms. The caller can, of course,
222         # break this assumption by playing silly buggers, but that's
223         # harder to do than doing it properly, and harder to check
224         # for.
225         if (ref($self) eq "")
226         {
227                 # Class method. The new context is the next argument.
228                 $new_context = shift;
229         } else {
230                 # Instance method. The new context is $self.
231                 $new_context = $self;
232         }
233
234         # Save the old context, if any, on the stack
235         push @context_stack, $context if defined($context);
236
237         # Set the new context
238         $context = $new_context;
239 }
240
241 =item restore_context
242
243   &restore_context;
244
245 Restores the context set by C<&set_context>.
246
247 =cut
248 #'
249 sub restore_context
250 {
251         my $self = shift;
252
253         if ($#context_stack < 0)
254         {
255                 # Stack underflow.
256                 die "Context stack underflow";
257         }
258
259         # Pop the old context and set it.
260         $context = pop @context_stack;
261
262         # FIXME - Should this return something, like maybe the context
263         # that was current when this was called?
264 }
265
266 =item config
267
268   $value = C4::Context->config("config_variable");
269
270   $value = C4::Context->config_variable;
271
272 Returns the value of a variable specified in the configuration file
273 from which the current context was created.
274
275 The second form is more compact, but of course may conflict with
276 method names. If there is a configuration variable called "new", then
277 C<C4::Config-E<gt>new> will not return it.
278
279 =cut
280 #'
281 sub config
282 {
283         my $self = shift;
284         my $var = shift;                # The config variable to return
285
286         return undef if !defined($context->{"config"});
287                         # Presumably $self->{config} might be
288                         # undefined if the config file given to &new
289                         # didn't exist, and the caller didn't bother
290                         # to check the return value.
291
292         # Return the value of the requested config variable
293         return $context->{"config"}{$var};
294 }
295
296 =item preference
297
298   $sys_preference = C4::Context->preference("some_variable");
299
300 Looks up the value of the given system preference in the
301 systempreferences table of the Koha database, and returns it. If the
302 variable is not set, or in case of error, returns the undefined value.
303
304 =cut
305 #'
306 # FIXME - The preferences aren't likely to change over the lifetime of
307 # the script (and things might break if they did change), so perhaps
308 # this function should cache the results it finds.
309 sub preference
310 {
311         my $self = shift;
312         my $var = shift;                # The system preference to return
313         my $retval;                     # Return value
314         my $dbh = C4::Context->dbh;     # Database handle
315         my $sth;                        # Database query handle
316
317         # Look up systempreferences.variable==$var
318         $retval = $dbh->selectrow_array(<<EOT);
319                 SELECT  value
320                 FROM    systempreferences
321                 WHERE   variable='$var'
322                 LIMIT   1
323 EOT
324         return $retval;
325 }
326
327 # AUTOLOAD
328 # This implements C4::Config->foo, and simply returns
329 # C4::Context->config("foo"), as described in the documentation for
330 # &config, above.
331
332 # FIXME - Perhaps this should be extended to check &config first, and
333 # then &preference if that fails. OTOH, AUTOLOAD could lead to crappy
334 # code, so it'd probably be best to delete it altogether so as not to
335 # encourage people to use it.
336 sub AUTOLOAD
337 {
338         my $self = shift;
339
340         $AUTOLOAD =~ s/.*:://;          # Chop off the package name,
341                                         # leaving only the function name.
342         return $self->config($AUTOLOAD);
343 }
344
345 # _new_dbh
346 # Internal helper function (not a method!). This creates a new
347 # database connection from the data given in the current context, and
348 # returns it.
349 sub _new_dbh
350 {
351         my $db_driver = $context->{"config"}{"db_scheme"} || "mysql";
352                 # FIXME - It should be possible to use "MySQL" instead
353                 # of "mysql", "PostgreSQL" instead of "Pg", and so
354                 # forth.
355         my $db_name   = $context->{"config"}{"database"};
356         my $db_host   = $context->{"config"}{"hostname"};
357         my $db_user   = $context->{"config"}{"user"};
358         my $db_passwd = $context->{"config"}{"pass"};
359
360         return DBI->connect("DBI:$db_driver:$db_name:$db_host",
361                             $db_user, $db_passwd);
362 }
363
364 =item dbh
365
366   $dbh = C4::Context->dbh;
367
368 Returns a database handle connected to the Koha database for the
369 current context. If no connection has yet been made, this method
370 creates one, and connects to the database.
371
372 This database handle is cached for future use: if you call
373 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
374 times. If you need a second database handle, use C<&new_dbh> and
375 possibly C<&set_dbh>.
376
377 =cut
378 #'
379 sub dbh
380 {
381         my $self = shift;
382
383         # If there's already a database handle, return it.
384         return $context->{"dbh"} if defined($context->{"dbh"});
385
386         # No database handle yet. Create one.
387         $context->{"dbh"} = &_new_dbh();
388
389         return $context->{"dbh"};
390 }
391
392 =item new_dbh
393
394   $dbh = C4::Context->new_dbh;
395
396 Creates a new connection to the Koha database for the current context,
397 and returns the database handle (a C<DBI::db> object).
398
399 The handle is not saved anywhere: this method is strictly a
400 convenience function; the point is that it knows which database to
401 connect to so that the caller doesn't have to know.
402
403 =cut
404 #'
405 sub new_dbh
406 {
407         my $self = shift;
408
409         return &_new_dbh();
410 }
411
412 =item set_dbh
413
414   $my_dbh = C4::Connect->new_dbh;
415   C4::Connect->set_dbh($my_dbh);
416   ...
417   C4::Connect->restore_dbh;
418
419 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
420 C<&set_context> and C<&restore_context>.
421
422 C<&set_dbh> saves the current database handle on a stack, then sets
423 the current database handle to C<$my_dbh>.
424
425 C<$my_dbh> is assumed to be a good database handle.
426
427 =cut
428 #'
429 sub set_dbh
430 {
431         my $self = shift;
432         my $new_dbh = shift;
433
434         # Save the current database handle on the handle stack.
435         # We assume that $new_dbh is all good: if the caller wants to
436         # screw himself by passing an invalid handle, that's fine by
437         # us.
438         push @{$context->{"dbh_stack"}}, $context->{"dbh"};
439         $context->{"dbh"} = $new_dbh;
440 }
441
442 =item restore_dbh
443
444   C4::Context->restore_dbh;
445
446 Restores the database handle saved by an earlier call to
447 C<C4::Context-E<gt>set_dbh>.
448
449 =cut
450 #'
451 sub restore_dbh
452 {
453         my $self = shift;
454
455         if ($#{$context->{"dbh_stack"}} < 0)
456         {
457                 # Stack underflow
458                 die "DBH stack underflow";
459         }
460
461         # Pop the old database handle and set it.
462         $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
463
464         # FIXME - If it is determined that restore_context should
465         # return something, then this function should, too.
466 }
467
468 =item stopwords
469
470   $dbh = C4::Context->stopwords;
471
472 Returns a hash with stopwords.
473
474 This hash is cached for future use: if you call
475 C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
476
477 =cut
478 #'
479 sub stopwords
480 {
481         my $retval = {};
482
483         # If the hash already exists, return it.
484         return $context->{"stopwords"} if defined($context->{"stopwords"});
485
486         # No hash. Create one.
487         $context->{"stopwords"} = &_new_stopwords();
488
489         return $context->{"stopwords"};
490 }
491
492 # _new_stopwords
493 # Internal helper function (not a method!). This creates a new
494 # hash with stopwords
495 sub _new_stopwords
496 {
497         my $dbh = C4::Context->dbh;
498         my $stopwordlist;
499         my $sth = $dbh->prepare("select word from stopwords");
500         $sth->execute;
501         while (my $stopword = $sth->fetchrow_array) {
502                 my $retval = {};
503                 $stopwordlist->{$stopword} = uc($stopword);
504         }
505         return $stopwordlist;
506 }
507
508 1;
509 __END__
510
511 =back
512
513 =head1 ENVIRONMENT
514
515 =over 4
516
517 =item C<KOHA_CONF>
518
519 Specifies the configuration file to read.
520
521 =back
522
523 =head1 SEE ALSO
524
525 DBI(3)
526
527 =head1 AUTHOR
528
529 Andrew Arensburger <arensb at ooblick dot com>
530
531 =cut