Revert "Bug 8089: Cache sysprefs using Koha::Cache"
[koha.git] / C4 / Context.pm
1 package C4::Context;
2 # Copyright 2002 Katipo Communications
3 #
4 # This file is part of Koha.
5 #
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
19 use strict;
20 use warnings;
21 use vars qw($VERSION $AUTOLOAD $context @context_stack);
22
23 use Koha::Cache;
24
25 BEGIN {
26         if ($ENV{'HTTP_USER_AGENT'})    {
27                 require CGI::Carp;
28         # FIXME for future reference, CGI::Carp doc says
29         #  "Note that fatalsToBrowser does not work with mod_perl version 2.0 and higher."
30                 import CGI::Carp qw(fatalsToBrowser);
31                         sub handle_errors {
32                             my $msg = shift;
33                             my $debug_level;
34                             eval {C4::Context->dbh();};
35                             if ($@){
36                                 $debug_level = 1;
37                             } 
38                             else {
39                                 $debug_level =  C4::Context->preference("DebugLevel");
40                             }
41
42                 print q(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
43                             "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
44                        <html lang="en" xml:lang="en"  xmlns="http://www.w3.org/1999/xhtml">
45                        <head><title>Koha Error</title></head>
46                        <body>
47                 );
48                                 if ($debug_level eq "2"){
49                                         # debug 2 , print extra info too.
50                                         my %versions = get_versions();
51
52                 # a little example table with various version info";
53                                         print "
54                                                 <h1>Koha error</h1>
55                                                 <p>The following fatal error has occurred:</p> 
56                         <pre><code>$msg</code></pre>
57                                                 <table>
58                                                 <tr><th>Apache</th><td>  $versions{apacheVersion}</td></tr>
59                                                 <tr><th>Koha</th><td>    $versions{kohaVersion}</td></tr>
60                                                 <tr><th>Koha DB</th><td> $versions{kohaDbVersion}</td></tr>
61                                                 <tr><th>MySQL</th><td>   $versions{mysqlVersion}</td></tr>
62                                                 <tr><th>OS</th><td>      $versions{osVersion}</td></tr>
63                                                 <tr><th>Perl</th><td>    $versions{perlVersion}</td></tr>
64                                                 </table>";
65
66                                 } elsif ($debug_level eq "1"){
67                                         print "
68                                                 <h1>Koha error</h1>
69                                                 <p>The following fatal error has occurred:</p> 
70                         <pre><code>$msg</code></pre>";
71                                 } else {
72                                         print "<p>production mode - trapped fatal error</p>";
73                                 }       
74                 print "</body></html>";
75                         }
76                 #CGI::Carp::set_message(\&handle_errors);
77                 ## give a stack backtrace if KOHA_BACKTRACES is set
78                 ## can't rely on DebugLevel for this, as we're not yet connected
79                 if ($ENV{KOHA_BACKTRACES}) {
80                         $main::SIG{__DIE__} = \&CGI::Carp::confess;
81                 }
82     }   # else there is no browser to send fatals to!
83
84     $VERSION = '3.07.00.049';
85 }
86
87 use DBI;
88 use ZOOM;
89 use XML::Simple;
90 use C4::Boolean;
91 use C4::Debug;
92 use POSIX ();
93 use DateTime::TimeZone;
94
95 =head1 NAME
96
97 C4::Context - Maintain and manipulate the context of a Koha script
98
99 =head1 SYNOPSIS
100
101   use C4::Context;
102
103   use C4::Context("/path/to/koha-conf.xml");
104
105   $config_value = C4::Context->config("config_variable");
106
107   $koha_preference = C4::Context->preference("preference");
108
109   $db_handle = C4::Context->dbh;
110
111   $Zconn = C4::Context->Zconn;
112
113   $stopwordhash = C4::Context->stopwords;
114
115 =head1 DESCRIPTION
116
117 When a Koha script runs, it makes use of a certain number of things:
118 configuration settings in F</etc/koha/koha-conf.xml>, a connection to the Koha
119 databases, and so forth. These things make up the I<context> in which
120 the script runs.
121
122 This module takes care of setting up the context for a script:
123 figuring out which configuration file to load, and loading it, opening
124 a connection to the right database, and so forth.
125
126 Most scripts will only use one context. They can simply have
127
128   use C4::Context;
129
130 at the top.
131
132 Other scripts may need to use several contexts. For instance, if a
133 library has two databases, one for a certain collection, and the other
134 for everything else, it might be necessary for a script to use two
135 different contexts to search both databases. Such scripts should use
136 the C<&set_context> and C<&restore_context> functions, below.
137
138 By default, C4::Context reads the configuration from
139 F</etc/koha/koha-conf.xml>. This may be overridden by setting the C<$KOHA_CONF>
140 environment variable to the pathname of a configuration file to use.
141
142 =head1 METHODS
143
144 =cut
145
146 #'
147 # In addition to what is said in the POD above, a Context object is a
148 # reference-to-hash with the following fields:
149 #
150 # config
151 #    A reference-to-hash whose keys and values are the
152 #    configuration variables and values specified in the config
153 #    file (/etc/koha/koha-conf.xml).
154 # dbh
155 #    A handle to the appropriate database for this context.
156 # dbh_stack
157 #    Used by &set_dbh and &restore_dbh to hold other database
158 #    handles for this context.
159 # Zconn
160 #     A connection object for the Zebra server
161
162 # Koha's main configuration file koha-conf.xml
163 # is searched for according to this priority list:
164 #
165 # 1. Path supplied via use C4::Context '/path/to/koha-conf.xml'
166 # 2. Path supplied in KOHA_CONF environment variable.
167 # 3. Path supplied in INSTALLED_CONFIG_FNAME, as long
168 #    as value has changed from its default of 
169 #    '__KOHA_CONF_DIR__/koha-conf.xml', as happens
170 #    when Koha is installed in 'standard' or 'single'
171 #    mode.
172 # 4. Path supplied in CONFIG_FNAME.
173 #
174 # The first entry that refers to a readable file is used.
175
176 use constant CONFIG_FNAME => "/etc/koha/koha-conf.xml";
177                 # Default config file, if none is specified
178                 
179 my $INSTALLED_CONFIG_FNAME = '__KOHA_CONF_DIR__/koha-conf.xml';
180                 # path to config file set by installer
181                 # __KOHA_CONF_DIR__ is set by rewrite-confg.PL
182                 # when Koha is installed in 'standard' or 'single'
183                 # mode.  If Koha was installed in 'dev' mode, 
184                 # __KOHA_CONF_DIR__ is *not* rewritten; instead
185                 # developers should set the KOHA_CONF environment variable 
186
187 $context = undef;        # Initially, no context is set
188 @context_stack = ();        # Initially, no saved contexts
189
190
191 =head2 KOHAVERSION
192
193 returns the kohaversion stored in kohaversion.pl file
194
195 =cut
196
197 sub KOHAVERSION {
198     my $cgidir = C4::Context->intranetdir;
199
200     # Apparently the GIT code does not run out of a CGI-BIN subdirectory
201     # but distribution code does?  (Stan, 1jan08)
202     if(-d $cgidir . "/cgi-bin"){
203         my $cgidir .= "/cgi-bin";
204     }
205     
206     do $cgidir."/kohaversion.pl" || die "NO $cgidir/kohaversion.pl";
207     return kohaversion();
208 }
209 =head2 read_config_file
210
211 Reads the specified Koha config file. 
212
213 Returns an object containing the configuration variables. The object's
214 structure is a bit complex to the uninitiated ... take a look at the
215 koha-conf.xml file as well as the XML::Simple documentation for details. Or,
216 here are a few examples that may give you what you need:
217
218 The simple elements nested within the <config> element:
219
220     my $pass = $koha->{'config'}->{'pass'};
221
222 The <listen> elements:
223
224     my $listen = $koha->{'listen'}->{'biblioserver'}->{'content'};
225
226 The elements nested within the <server> element:
227
228     my $ccl2rpn = $koha->{'server'}->{'biblioserver'}->{'cql2rpn'};
229
230 Returns undef in case of error.
231
232 =cut
233
234 sub read_config_file {          # Pass argument naming config file to read
235     my $koha = XMLin(shift, keyattr => ['id'], forcearray => ['listen', 'server', 'serverinfo'], suppressempty => '');
236
237     if (Koha::Cache->is_cache_active()) {
238         my $cache = Koha::Cache->new();
239         $cache->set_in_cache('kohaconf', $koha) if defined $cache;
240     }
241
242     return $koha;                       # Return value: ref-to-hash holding the configuration
243 }
244
245 # db_scheme2dbi
246 # Translates the full text name of a database into de appropiate dbi name
247
248 sub db_scheme2dbi {
249     my $name = shift;
250     # for instance, we support only mysql, so don't care checking
251     return "mysql";
252     for ($name) {
253 # FIXME - Should have other databases. 
254         if (/mysql/) { return("mysql"); }
255         if (/Postgres|Pg|PostgresSQL/) { return("Pg"); }
256         if (/oracle/) { return("Oracle"); }
257     }
258     return undef;         # Just in case
259 }
260
261 sub import {
262     # Create the default context ($C4::Context::Context)
263     # the first time the module is called
264     # (a config file can be optionaly passed)
265
266     # default context allready exists? 
267     return if $context;
268
269     # no ? so load it!
270     my ($pkg,$config_file) = @_ ;
271     my $new_ctx = __PACKAGE__->new($config_file);
272     return unless $new_ctx;
273
274     # if successfully loaded, use it by default
275     $new_ctx->set_context;
276     1;
277 }
278
279 =head2 new
280
281   $context = new C4::Context;
282   $context = new C4::Context("/path/to/koha-conf.xml");
283
284 Allocates a new context. Initializes the context from the specified
285 file, which defaults to either the file given by the C<$KOHA_CONF>
286 environment variable, or F</etc/koha/koha-conf.xml>.
287
288 It saves the koha-conf.xml values in the cache (if configured) and uses
289 those values until them expire and re-reads them.
290
291 C<&new> does not set this context as the new default context; for
292 that, use C<&set_context>.
293
294 =cut
295
296 #'
297 # Revision History:
298 # 2004-08-10 A. Tarallo: Added check if the conf file is not empty
299 sub new {
300     my $class = shift;
301     my $conf_fname = shift;        # Config file to load
302     my $self = {};
303
304     # check that the specified config file exists and is not empty
305     undef $conf_fname unless 
306         (defined $conf_fname && -s $conf_fname);
307     # Figure out a good config file to load if none was specified.
308     if (!defined($conf_fname))
309     {
310         # If the $KOHA_CONF environment variable is set, use
311         # that. Otherwise, use the built-in default.
312         if (exists $ENV{"KOHA_CONF"} and $ENV{'KOHA_CONF'} and -s  $ENV{"KOHA_CONF"}) {
313             $conf_fname = $ENV{"KOHA_CONF"};
314         } elsif ($INSTALLED_CONFIG_FNAME !~ /__KOHA_CONF_DIR/ and -s $INSTALLED_CONFIG_FNAME) {
315             # NOTE: be careful -- don't change __KOHA_CONF_DIR in the above
316             # regex to anything else -- don't want installer to rewrite it
317             $conf_fname = $INSTALLED_CONFIG_FNAME;
318         } elsif (-s CONFIG_FNAME) {
319             $conf_fname = CONFIG_FNAME;
320         } else {
321             warn "unable to locate Koha configuration file koha-conf.xml";
322             return undef;
323         }
324     }
325     
326     if (Koha::Cache->is_cache_active()) {
327         # retrieve from cache
328         my $cache = Koha::Cache->new();
329         $self = $cache->get_from_cache('kohaconf') if defined $cache;
330         $self = { };
331     }
332     if (!keys %$self) {
333         # not cached yet
334         $self = read_config_file($conf_fname);
335     }
336
337     $self->{"config_file"} = $conf_fname;
338     warn "read_config_file($conf_fname) returned undef" if !defined($self->{"config"});
339     return undef if !defined($self->{"config"});
340
341     $self->{"dbh"} = undef;        # Database handle
342     $self->{"Zconn"} = undef;    # Zebra Connections
343     $self->{"stopwords"} = undef; # stopwords list
344     $self->{"marcfromkohafield"} = undef; # the hash with relations between koha table fields and MARC field/subfield
345     $self->{"userenv"} = undef;        # User env
346     $self->{"activeuser"} = undef;        # current active user
347     $self->{"shelves"} = undef;
348     $self->{tz} = undef; # local timezone object
349
350     bless $self, $class;
351     return $self;
352 }
353
354 =head2 set_context
355
356   $context = new C4::Context;
357   $context->set_context();
358 or
359   set_context C4::Context $context;
360
361   ...
362   restore_context C4::Context;
363
364 In some cases, it might be necessary for a script to use multiple
365 contexts. C<&set_context> saves the current context on a stack, then
366 sets the context to C<$context>, which will be used in future
367 operations. To restore the previous context, use C<&restore_context>.
368
369 =cut
370
371 #'
372 sub set_context
373 {
374     my $self = shift;
375     my $new_context;    # The context to set
376
377     # Figure out whether this is a class or instance method call.
378     #
379     # We're going to make the assumption that control got here
380     # through valid means, i.e., that the caller used an instance
381     # or class method call, and that control got here through the
382     # usual inheritance mechanisms. The caller can, of course,
383     # break this assumption by playing silly buggers, but that's
384     # harder to do than doing it properly, and harder to check
385     # for.
386     if (ref($self) eq "")
387     {
388         # Class method. The new context is the next argument.
389         $new_context = shift;
390     } else {
391         # Instance method. The new context is $self.
392         $new_context = $self;
393     }
394
395     # Save the old context, if any, on the stack
396     push @context_stack, $context if defined($context);
397
398     # Set the new context
399     $context = $new_context;
400 }
401
402 =head2 restore_context
403
404   &restore_context;
405
406 Restores the context set by C<&set_context>.
407
408 =cut
409
410 #'
411 sub restore_context
412 {
413     my $self = shift;
414
415     if ($#context_stack < 0)
416     {
417         # Stack underflow.
418         die "Context stack underflow";
419     }
420
421     # Pop the old context and set it.
422     $context = pop @context_stack;
423
424     # FIXME - Should this return something, like maybe the context
425     # that was current when this was called?
426 }
427
428 =head2 config
429
430   $value = C4::Context->config("config_variable");
431
432   $value = C4::Context->config_variable;
433
434 Returns the value of a variable specified in the configuration file
435 from which the current context was created.
436
437 The second form is more compact, but of course may conflict with
438 method names. If there is a configuration variable called "new", then
439 C<C4::Config-E<gt>new> will not return it.
440
441 =cut
442
443 sub _common_config ($$) {
444         my $var = shift;
445         my $term = shift;
446     return undef if !defined($context->{$term});
447        # Presumably $self->{$term} might be
448        # undefined if the config file given to &new
449        # didn't exist, and the caller didn't bother
450        # to check the return value.
451
452     # Return the value of the requested config variable
453     return $context->{$term}->{$var};
454 }
455
456 sub config {
457         return _common_config($_[1],'config');
458 }
459 sub zebraconfig {
460         return _common_config($_[1],'server');
461 }
462 sub ModZebrations {
463         return _common_config($_[1],'serverinfo');
464 }
465
466 =head2 preference
467
468   $sys_preference = C4::Context->preference('some_variable');
469
470 Looks up the value of the given system preference in the
471 systempreferences table of the Koha database, and returns it. If the
472 variable is not set or does not exist, undef is returned.
473
474 In case of an error, this may return 0.
475
476 Note: It is impossible to tell the difference between system
477 preferences which do not exist, and those whose values are set to NULL
478 with this method.
479
480 =cut
481
482 # FIXME: running this under mod_perl will require a means of
483 # flushing the caching mechanism.
484
485 my %sysprefs;
486
487 sub preference {
488     my $self = shift;
489     my $var  = lc(shift);                          # The system preference to return
490
491     if (exists $sysprefs{$var}) {
492         return $sysprefs{$var};
493     }
494
495     my $dbh  = C4::Context->dbh or return 0;
496
497     # Look up systempreferences.variable==$var
498     my $sql = <<'END_SQL';
499         SELECT    value
500         FROM    systempreferences
501         WHERE    variable=?
502         LIMIT    1
503 END_SQL
504     $sysprefs{$var} = $dbh->selectrow_array( $sql, {}, $var );
505     return $sysprefs{$var};
506 }
507
508 sub boolean_preference ($) {
509     my $self = shift;
510     my $var = shift;        # The system preference to return
511     my $it = preference($self, $var);
512     return defined($it)? C4::Boolean::true_p($it): undef;
513 }
514
515 =head2 clear_syspref_cache
516
517   C4::Context->clear_syspref_cache();
518
519 cleans the internal cache of sysprefs. Please call this method if
520 you update the systempreferences table. Otherwise, your new changes
521 will not be seen by this process.
522
523 =cut
524
525 sub clear_syspref_cache {
526     %sysprefs = ();
527 }
528
529 =head2 set_preference
530
531   C4::Context->set_preference( $variable, $value );
532
533 This updates a preference's value both in the systempreferences table and in
534 the sysprefs cache.
535
536 =cut
537
538 sub set_preference {
539     my $self = shift;
540     my $var = lc(shift);
541     my $value = shift;
542
543     my $dbh = C4::Context->dbh or return 0;
544
545     my $type = $dbh->selectrow_array( "SELECT type FROM systempreferences WHERE variable = ?", {}, $var );
546
547     $value = 0 if ( $type && $type eq 'YesNo' && $value eq '' );
548
549     my $sth = $dbh->prepare( "
550       INSERT INTO systempreferences
551         ( variable, value )
552         VALUES( ?, ? )
553         ON DUPLICATE KEY UPDATE value = VALUES(value)
554     " );
555
556     if($sth->execute( $var, $value )) {
557         $sysprefs{$var} = $value;
558     }
559     $sth->finish;
560 }
561
562 # AUTOLOAD
563 # This implements C4::Config->foo, and simply returns
564 # C4::Context->config("foo"), as described in the documentation for
565 # &config, above.
566
567 # FIXME - Perhaps this should be extended to check &config first, and
568 # then &preference if that fails. OTOH, AUTOLOAD could lead to crappy
569 # code, so it'd probably be best to delete it altogether so as not to
570 # encourage people to use it.
571 sub AUTOLOAD
572 {
573     my $self = shift;
574
575     $AUTOLOAD =~ s/.*:://;        # Chop off the package name,
576                     # leaving only the function name.
577     return $self->config($AUTOLOAD);
578 }
579
580 =head2 Zconn
581
582   $Zconn = C4::Context->Zconn
583
584 Returns a connection to the Zebra database for the current
585 context. If no connection has yet been made, this method 
586 creates one and connects.
587
588 C<$self> 
589
590 C<$server> one of the servers defined in the koha-conf.xml file
591
592 C<$async> whether this is a asynchronous connection
593
594 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
595
596
597 =cut
598
599 sub Zconn {
600     my $self=shift;
601     my $server=shift;
602     my $async=shift;
603     my $auth=shift;
604     my $piggyback=shift;
605     my $syntax=shift;
606     if ( defined($context->{"Zconn"}->{$server}) && (0 == $context->{"Zconn"}->{$server}->errcode()) ) {
607         return $context->{"Zconn"}->{$server};
608     # No connection object or it died. Create one.
609     }else {
610         # release resources if we're closing a connection and making a new one
611         # FIXME: this needs to be smarter -- an error due to a malformed query or
612         # a missing index does not necessarily require us to close the connection
613         # and make a new one, particularly for a batch job.  However, at
614         # first glance it does not look like there's a way to easily check
615         # the basic health of a ZOOM::Connection
616         $context->{"Zconn"}->{$server}->destroy() if defined($context->{"Zconn"}->{$server});
617
618         $context->{"Zconn"}->{$server} = &_new_Zconn($server,$async,$auth,$piggyback,$syntax);
619         return $context->{"Zconn"}->{$server};
620     }
621 }
622
623 =head2 _new_Zconn
624
625 $context->{"Zconn"} = &_new_Zconn($server,$async);
626
627 Internal function. Creates a new database connection from the data given in the current context and returns it.
628
629 C<$server> one of the servers defined in the koha-conf.xml file
630
631 C<$async> whether this is a asynchronous connection
632
633 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
634
635 =cut
636
637 sub _new_Zconn {
638     my ($server,$async,$auth,$piggyback,$syntax) = @_;
639
640     my $tried=0; # first attempt
641     my $Zconn; # connection object
642     $server = "biblioserver" unless $server;
643     $syntax = "usmarc" unless $syntax;
644
645     my $host = $context->{'listen'}->{$server}->{'content'};
646     my $servername = $context->{"config"}->{$server};
647     my $user = $context->{"serverinfo"}->{$server}->{"user"};
648     my $password = $context->{"serverinfo"}->{$server}->{"password"};
649  $auth = 1 if($user && $password);   
650     retry:
651     eval {
652         # set options
653         my $o = new ZOOM::Options();
654         $o->option(user=>$user) if $auth;
655         $o->option(password=>$password) if $auth;
656         $o->option(async => 1) if $async;
657         $o->option(count => $piggyback) if $piggyback;
658         $o->option(cqlfile=> $context->{"server"}->{$server}->{"cql2rpn"});
659         $o->option(cclfile=> $context->{"serverinfo"}->{$server}->{"ccl2rpn"});
660         $o->option(preferredRecordSyntax => $syntax);
661         $o->option(elementSetName => "F"); # F for 'full' as opposed to B for 'brief'
662         $o->option(databaseName => ($servername?$servername:"biblios"));
663
664         # create a new connection object
665         $Zconn= create ZOOM::Connection($o);
666
667         # forge to server
668         $Zconn->connect($host, 0);
669
670         # check for errors and warn
671         if ($Zconn->errcode() !=0) {
672             warn "something wrong with the connection: ". $Zconn->errmsg();
673         }
674
675     };
676 #     if ($@) {
677 #         # Koha manages the Zebra server -- this doesn't work currently for me because of permissions issues
678 #         # Also, I'm skeptical about whether it's the best approach
679 #         warn "problem with Zebra";
680 #         if ( C4::Context->preference("ManageZebra") ) {
681 #             if ($@->code==10000 && $tried==0) { ##No connection try restarting Zebra
682 #                 $tried=1;
683 #                 warn "trying to restart Zebra";
684 #                 my $res=system("zebrasrv -f $ENV{'KOHA_CONF'} >/koha/log/zebra-error.log");
685 #                 goto "retry";
686 #             } else {
687 #                 warn "Error ", $@->code(), ": ", $@->message(), "\n";
688 #                 $Zconn="error";
689 #                 return $Zconn;
690 #             }
691 #         }
692 #     }
693     return $Zconn;
694 }
695
696 # _new_dbh
697 # Internal helper function (not a method!). This creates a new
698 # database connection from the data given in the current context, and
699 # returns it.
700 sub _new_dbh
701 {
702
703     ## $context
704     ## correct name for db_schme        
705     my $db_driver;
706     if ($context->config("db_scheme")){
707         $db_driver=db_scheme2dbi($context->config("db_scheme"));
708     }else{
709         $db_driver="mysql";
710     }
711
712     my $db_name   = $context->config("database");
713     my $db_host   = $context->config("hostname");
714     my $db_port   = $context->config("port") || '';
715     my $db_user   = $context->config("user");
716     my $db_passwd = $context->config("pass");
717     # MJR added or die here, as we can't work without dbh
718     my $dbh= DBI->connect("DBI:$db_driver:dbname=$db_name;host=$db_host;port=$db_port",
719     $db_user, $db_passwd, {'RaiseError' => $ENV{DEBUG}?1:0 }) or die $DBI::errstr;
720         my $tz = $ENV{TZ};
721     if ( $db_driver eq 'mysql' ) { 
722         # Koha 3.0 is utf-8, so force utf8 communication between mySQL and koha, whatever the mysql default config.
723         # this is better than modifying my.cnf (and forcing all communications to be in utf8)
724         $dbh->{'mysql_enable_utf8'}=1; #enable
725         $dbh->do("set NAMES 'utf8'");
726         ($tz) and $dbh->do(qq(SET time_zone = "$tz"));
727     }
728     elsif ( $db_driver eq 'Pg' ) {
729             $dbh->do( "set client_encoding = 'UTF8';" );
730         ($tz) and $dbh->do(qq(SET TIME ZONE = "$tz"));
731     }
732     return $dbh;
733 }
734
735 =head2 dbh
736
737   $dbh = C4::Context->dbh;
738
739 Returns a database handle connected to the Koha database for the
740 current context. If no connection has yet been made, this method
741 creates one, and connects to the database.
742
743 This database handle is cached for future use: if you call
744 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
745 times. If you need a second database handle, use C<&new_dbh> and
746 possibly C<&set_dbh>.
747
748 =cut
749
750 #'
751 sub dbh
752 {
753     my $self = shift;
754     my $sth;
755
756     if (defined($context->{"dbh"}) && $context->{"dbh"}->ping()) {
757         return $context->{"dbh"};
758     }
759
760     # No database handle or it died . Create one.
761     $context->{"dbh"} = &_new_dbh();
762
763     return $context->{"dbh"};
764 }
765
766 =head2 new_dbh
767
768   $dbh = C4::Context->new_dbh;
769
770 Creates a new connection to the Koha database for the current context,
771 and returns the database handle (a C<DBI::db> object).
772
773 The handle is not saved anywhere: this method is strictly a
774 convenience function; the point is that it knows which database to
775 connect to so that the caller doesn't have to know.
776
777 =cut
778
779 #'
780 sub new_dbh
781 {
782     my $self = shift;
783
784     return &_new_dbh();
785 }
786
787 =head2 set_dbh
788
789   $my_dbh = C4::Connect->new_dbh;
790   C4::Connect->set_dbh($my_dbh);
791   ...
792   C4::Connect->restore_dbh;
793
794 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
795 C<&set_context> and C<&restore_context>.
796
797 C<&set_dbh> saves the current database handle on a stack, then sets
798 the current database handle to C<$my_dbh>.
799
800 C<$my_dbh> is assumed to be a good database handle.
801
802 =cut
803
804 #'
805 sub set_dbh
806 {
807     my $self = shift;
808     my $new_dbh = shift;
809
810     # Save the current database handle on the handle stack.
811     # We assume that $new_dbh is all good: if the caller wants to
812     # screw himself by passing an invalid handle, that's fine by
813     # us.
814     push @{$context->{"dbh_stack"}}, $context->{"dbh"};
815     $context->{"dbh"} = $new_dbh;
816 }
817
818 =head2 restore_dbh
819
820   C4::Context->restore_dbh;
821
822 Restores the database handle saved by an earlier call to
823 C<C4::Context-E<gt>set_dbh>.
824
825 =cut
826
827 #'
828 sub restore_dbh
829 {
830     my $self = shift;
831
832     if ($#{$context->{"dbh_stack"}} < 0)
833     {
834         # Stack underflow
835         die "DBH stack underflow";
836     }
837
838     # Pop the old database handle and set it.
839     $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
840
841     # FIXME - If it is determined that restore_context should
842     # return something, then this function should, too.
843 }
844
845 =head2 marcfromkohafield
846
847   $dbh = C4::Context->marcfromkohafield;
848
849 Returns a hash with marcfromkohafield.
850
851 This hash is cached for future use: if you call
852 C<C4::Context-E<gt>marcfromkohafield> twice, you will get the same hash without real DB access
853
854 =cut
855
856 #'
857 sub marcfromkohafield
858 {
859     my $retval = {};
860
861     # If the hash already exists, return it.
862     return $context->{"marcfromkohafield"} if defined($context->{"marcfromkohafield"});
863
864     # No hash. Create one.
865     $context->{"marcfromkohafield"} = &_new_marcfromkohafield();
866
867     return $context->{"marcfromkohafield"};
868 }
869
870 # _new_marcfromkohafield
871 # Internal helper function (not a method!). This creates a new
872 # hash with stopwords
873 sub _new_marcfromkohafield
874 {
875     my $dbh = C4::Context->dbh;
876     my $marcfromkohafield;
877     my $sth = $dbh->prepare("select frameworkcode,kohafield,tagfield,tagsubfield from marc_subfield_structure where kohafield > ''");
878     $sth->execute;
879     while (my ($frameworkcode,$kohafield,$tagfield,$tagsubfield) = $sth->fetchrow) {
880         my $retval = {};
881         $marcfromkohafield->{$frameworkcode}->{$kohafield} = [$tagfield,$tagsubfield];
882     }
883     return $marcfromkohafield;
884 }
885
886 =head2 stopwords
887
888   $dbh = C4::Context->stopwords;
889
890 Returns a hash with stopwords.
891
892 This hash is cached for future use: if you call
893 C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
894
895 =cut
896
897 #'
898 sub stopwords
899 {
900     my $retval = {};
901
902     # If the hash already exists, return it.
903     return $context->{"stopwords"} if defined($context->{"stopwords"});
904
905     # No hash. Create one.
906     $context->{"stopwords"} = &_new_stopwords();
907
908     return $context->{"stopwords"};
909 }
910
911 # _new_stopwords
912 # Internal helper function (not a method!). This creates a new
913 # hash with stopwords
914 sub _new_stopwords
915 {
916     my $dbh = C4::Context->dbh;
917     my $stopwordlist;
918     my $sth = $dbh->prepare("select word from stopwords");
919     $sth->execute;
920     while (my $stopword = $sth->fetchrow_array) {
921         $stopwordlist->{$stopword} = uc($stopword);
922     }
923     $stopwordlist->{A} = "A" unless $stopwordlist;
924     return $stopwordlist;
925 }
926
927 =head2 userenv
928
929   C4::Context->userenv;
930
931 Retrieves a hash for user environment variables.
932
933 This hash shall be cached for future use: if you call
934 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
935
936 =cut
937
938 #'
939 sub userenv {
940     my $var = $context->{"activeuser"};
941     return $context->{"userenv"}->{$var} if (defined $var and defined $context->{"userenv"}->{$var});
942     # insecure=1 management
943     if ($context->{"dbh"} && $context->preference('insecure') eq 'yes') {
944         my %insecure;
945         $insecure{flags} = '16382';
946         $insecure{branchname} ='Insecure';
947         $insecure{number} ='0';
948         $insecure{cardnumber} ='0';
949         $insecure{id} = 'insecure';
950         $insecure{branch} = 'INS';
951         $insecure{emailaddress} = 'test@mode.insecure.com';
952         return \%insecure;
953     } else {
954         return;
955     }
956 }
957
958 =head2 set_userenv
959
960   C4::Context->set_userenv($usernum, $userid, $usercnum, $userfirstname, 
961                   $usersurname, $userbranch, $userflags, $emailaddress);
962
963 Establish a hash of user environment variables.
964
965 set_userenv is called in Auth.pm
966
967 =cut
968
969 #'
970 sub set_userenv {
971     my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter)= @_;
972     my $var=$context->{"activeuser"};
973     my $cell = {
974         "number"     => $usernum,
975         "id"         => $userid,
976         "cardnumber" => $usercnum,
977         "firstname"  => $userfirstname,
978         "surname"    => $usersurname,
979         #possibly a law problem
980         "branch"     => $userbranch,
981         "branchname" => $branchname,
982         "flags"      => $userflags,
983         "emailaddress"     => $emailaddress,
984         "branchprinter"    => $branchprinter
985     };
986     $context->{userenv}->{$var} = $cell;
987     return $cell;
988 }
989
990 sub set_shelves_userenv ($$) {
991         my ($type, $shelves) = @_ or return undef;
992         my $activeuser = $context->{activeuser} or return undef;
993         $context->{userenv}->{$activeuser}->{barshelves} = $shelves if $type eq 'bar';
994         $context->{userenv}->{$activeuser}->{pubshelves} = $shelves if $type eq 'pub';
995         $context->{userenv}->{$activeuser}->{totshelves} = $shelves if $type eq 'tot';
996 }
997
998 sub get_shelves_userenv () {
999         my $active;
1000         unless ($active = $context->{userenv}->{$context->{activeuser}}) {
1001                 $debug and warn "get_shelves_userenv cannot retrieve context->{userenv}->{context->{activeuser}}";
1002                 return undef;
1003         }
1004         my $totshelves = $active->{totshelves} or undef;
1005         my $pubshelves = $active->{pubshelves} or undef;
1006         my $barshelves = $active->{barshelves} or undef;
1007         return ($totshelves, $pubshelves, $barshelves);
1008 }
1009
1010 =head2 _new_userenv
1011
1012   C4::Context->_new_userenv($session);  # FIXME: This calling style is wrong for what looks like an _internal function
1013
1014 Builds a hash for user environment variables.
1015
1016 This hash shall be cached for future use: if you call
1017 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
1018
1019 _new_userenv is called in Auth.pm
1020
1021 =cut
1022
1023 #'
1024 sub _new_userenv
1025 {
1026     shift;  # Useless except it compensates for bad calling style
1027     my ($sessionID)= @_;
1028      $context->{"activeuser"}=$sessionID;
1029 }
1030
1031 =head2 _unset_userenv
1032
1033   C4::Context->_unset_userenv;
1034
1035 Destroys the hash for activeuser user environment variables.
1036
1037 =cut
1038
1039 #'
1040
1041 sub _unset_userenv
1042 {
1043     my ($sessionID)= @_;
1044     undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
1045 }
1046
1047
1048 =head2 get_versions
1049
1050   C4::Context->get_versions
1051
1052 Gets various version info, for core Koha packages, Currently called from carp handle_errors() sub, to send to browser if 'DebugLevel' syspref is set to '2'.
1053
1054 =cut
1055
1056 #'
1057
1058 # A little example sub to show more debugging info for CGI::Carp
1059 sub get_versions {
1060     my %versions;
1061     $versions{kohaVersion}  = KOHAVERSION();
1062     $versions{kohaDbVersion} = C4::Context->preference('version');
1063     $versions{osVersion} = join(" ", POSIX::uname());
1064     $versions{perlVersion} = $];
1065     {
1066         no warnings qw(exec); # suppress warnings if unable to find a program in $PATH
1067         $versions{mysqlVersion}  = `mysql -V`;
1068         $versions{apacheVersion} = `httpd -v`;
1069         $versions{apacheVersion} = `httpd2 -v`            unless  $versions{apacheVersion} ;
1070         $versions{apacheVersion} = `apache2 -v`           unless  $versions{apacheVersion} ;
1071         $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless  $versions{apacheVersion} ;
1072     }
1073     return %versions;
1074 }
1075
1076
1077 =head2 tz
1078
1079   C4::Context->tz
1080
1081   Returns a DateTime::TimeZone object for the system timezone
1082
1083 =cut
1084
1085 sub tz {
1086     my $self = shift;
1087     if (!defined $context->{tz}) {
1088         $context->{tz} = DateTime::TimeZone->new(name => 'local');
1089     }
1090     return $context->{tz};
1091 }
1092
1093
1094
1095 1;
1096 __END__
1097
1098 =head1 ENVIRONMENT
1099
1100 =head2 C<KOHA_CONF>
1101
1102 Specifies the configuration file to read.
1103
1104 =head1 SEE ALSO
1105
1106 XML::Simple
1107
1108 =head1 AUTHORS
1109
1110 Andrew Arensburger <arensb at ooblick dot com>
1111
1112 Joshua Ferraro <jmf at liblime dot com>
1113
1114 =cut