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