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