Bug 11944: (RM followup) Missing dependency in C4::Context
[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 DBI;
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
677
678 C<$self> 
679
680 C<$server> one of the servers defined in the koha-conf.xml file
681
682 C<$async> whether this is a asynchronous connection
683
684 =cut
685
686 sub Zconn {
687     my ($self, $server, $async ) = @_;
688     my $cache_key = join ('::', (map { $_ // '' } ($server, $async )));
689     if ( (!defined($ENV{GATEWAY_INTERFACE})) && defined($context->{"Zconn"}->{$cache_key}) && (0 == $context->{"Zconn"}->{$cache_key}->errcode()) ) {
690         # if we are running the script from the commandline, lets try to use the caching
691         return $context->{"Zconn"}->{$cache_key};
692     }
693     $context->{"Zconn"}->{$cache_key}->destroy() if defined($context->{"Zconn"}->{$cache_key}); #destroy old connection before making a new one
694     $context->{"Zconn"}->{$cache_key} = &_new_Zconn( $server, $async );
695     return $context->{"Zconn"}->{$cache_key};
696 }
697
698 =head2 _new_Zconn
699
700 $context->{"Zconn"} = &_new_Zconn($server,$async);
701
702 Internal function. Creates a new database connection from the data given in the current context and returns it.
703
704 C<$server> one of the servers defined in the koha-conf.xml file
705
706 C<$async> whether this is a asynchronous connection
707
708 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
709
710 =cut
711
712 sub _new_Zconn {
713     my ( $server, $async ) = @_;
714
715     my $tried=0; # first attempt
716     my $Zconn; # connection object
717     my $elementSetName;
718     my $index_mode;
719     my $syntax;
720
721     $server //= "biblioserver";
722
723     if ( $server eq 'biblioserver' ) {
724         $index_mode = $context->{'config'}->{'zebra_bib_index_mode'} // 'dom';
725     } elsif ( $server eq 'authorityserver' ) {
726         $index_mode = $context->{'config'}->{'zebra_auth_index_mode'} // 'dom';
727     }
728
729     if ( $index_mode eq 'grs1' ) {
730         $elementSetName = 'F';
731         $syntax = ( $context->preference("marcflavour") eq 'UNIMARC' )
732                 ? 'unimarc'
733                 : 'usmarc';
734
735     } else { # $index_mode eq 'dom'
736         $syntax = 'xml';
737         $elementSetName = 'marcxml';
738     }
739
740     my $host = $context->{'listen'}->{$server}->{'content'};
741     my $user = $context->{"serverinfo"}->{$server}->{"user"};
742     my $password = $context->{"serverinfo"}->{$server}->{"password"};
743     eval {
744         # set options
745         my $o = new ZOOM::Options();
746         $o->option(user => $user) if $user && $password;
747         $o->option(password => $password) if $user && $password;
748         $o->option(async => 1) if $async;
749         $o->option(cqlfile=> $context->{"server"}->{$server}->{"cql2rpn"});
750         $o->option(cclfile=> $context->{"serverinfo"}->{$server}->{"ccl2rpn"});
751         $o->option(preferredRecordSyntax => $syntax);
752         $o->option(elementSetName => $elementSetName) if $elementSetName;
753         $o->option(databaseName => $context->{"config"}->{$server}||"biblios");
754
755         # create a new connection object
756         $Zconn= create ZOOM::Connection($o);
757
758         # forge to server
759         $Zconn->connect($host, 0);
760
761         # check for errors and warn
762         if ($Zconn->errcode() !=0) {
763             warn "something wrong with the connection: ". $Zconn->errmsg();
764         }
765     };
766     return $Zconn;
767 }
768
769 # _new_dbh
770 # Internal helper function (not a method!). This creates a new
771 # database connection from the data given in the current context, and
772 # returns it.
773 sub _new_dbh
774 {
775
776     ## $context
777     ## correct name for db_scheme
778     my $db_driver = $context->{db_driver};
779
780     my $db_name   = $context->config("database");
781     my $db_host   = $context->config("hostname");
782     my $db_port   = $context->config("port") || '';
783     my $db_user   = $context->config("user");
784     my $db_passwd = $context->config("pass");
785     # MJR added or die here, as we can't work without dbh
786     my $dbh = DBI->connect("DBI:$db_driver:dbname=$db_name;host=$db_host;port=$db_port",
787     $db_user, $db_passwd, {'RaiseError' => $ENV{DEBUG}?1:0 }) or die $DBI::errstr;
788
789     # Check for the existence of a systempreference table; if we don't have this, we don't
790     # have a valid database and should not set RaiseError in order to allow the installer
791     # to run; installer will not run otherwise since we raise all db errors
792
793     eval {
794                 local $dbh->{PrintError} = 0;
795                 local $dbh->{RaiseError} = 1;
796                 $dbh->do(qq{SELECT * FROM systempreferences WHERE 1 = 0 });
797     };
798
799     if ($@) {
800         $dbh->{RaiseError} = 0;
801     }
802
803     if ( $db_driver eq 'mysql' ) {
804         $dbh->{mysql_auto_reconnect} = 1;
805     }
806
807         my $tz = $ENV{TZ};
808     if ( $db_driver eq 'mysql' ) { 
809         # Koha 3.0 is utf-8, so force utf8 communication between mySQL and koha, whatever the mysql default config.
810         # this is better than modifying my.cnf (and forcing all communications to be in utf8)
811         $dbh->{'mysql_enable_utf8'}=1; #enable
812         $dbh->do("set NAMES 'utf8'");
813         ($tz) and $dbh->do(qq(SET time_zone = "$tz"));
814     }
815     elsif ( $db_driver eq 'Pg' ) {
816             $dbh->do( "set client_encoding = 'UTF8';" );
817         ($tz) and $dbh->do(qq(SET TIME ZONE = "$tz"));
818     }
819     return $dbh;
820 }
821
822 =head2 dbh
823
824   $dbh = C4::Context->dbh;
825
826 Returns a database handle connected to the Koha database for the
827 current context. If no connection has yet been made, this method
828 creates one, and connects to the database.
829
830 This database handle is cached for future use: if you call
831 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
832 times. If you need a second database handle, use C<&new_dbh> and
833 possibly C<&set_dbh>.
834
835 =cut
836
837 #'
838 sub dbh
839 {
840     my $self = shift;
841     my $params = shift;
842     my $sth;
843
844     unless ( $params->{new} ) {
845         if ( defined($context->{db_driver}) && $context->{db_driver} eq 'mysql' && $context->{"dbh"} ) {
846             return $context->{"dbh"};
847         } elsif ( defined($context->{"dbh"}) && $context->{"dbh"}->ping() ) {
848             return $context->{"dbh"};
849         }
850     }
851
852     # No database handle or it died . Create one.
853     $context->{"dbh"} = &_new_dbh();
854
855     return $context->{"dbh"};
856 }
857
858 =head2 new_dbh
859
860   $dbh = C4::Context->new_dbh;
861
862 Creates a new connection to the Koha database for the current context,
863 and returns the database handle (a C<DBI::db> object).
864
865 The handle is not saved anywhere: this method is strictly a
866 convenience function; the point is that it knows which database to
867 connect to so that the caller doesn't have to know.
868
869 =cut
870
871 #'
872 sub new_dbh
873 {
874     my $self = shift;
875
876     return &_new_dbh();
877 }
878
879 =head2 set_dbh
880
881   $my_dbh = C4::Connect->new_dbh;
882   C4::Connect->set_dbh($my_dbh);
883   ...
884   C4::Connect->restore_dbh;
885
886 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
887 C<&set_context> and C<&restore_context>.
888
889 C<&set_dbh> saves the current database handle on a stack, then sets
890 the current database handle to C<$my_dbh>.
891
892 C<$my_dbh> is assumed to be a good database handle.
893
894 =cut
895
896 #'
897 sub set_dbh
898 {
899     my $self = shift;
900     my $new_dbh = shift;
901
902     # Save the current database handle on the handle stack.
903     # We assume that $new_dbh is all good: if the caller wants to
904     # screw himself by passing an invalid handle, that's fine by
905     # us.
906     push @{$context->{"dbh_stack"}}, $context->{"dbh"};
907     $context->{"dbh"} = $new_dbh;
908 }
909
910 =head2 restore_dbh
911
912   C4::Context->restore_dbh;
913
914 Restores the database handle saved by an earlier call to
915 C<C4::Context-E<gt>set_dbh>.
916
917 =cut
918
919 #'
920 sub restore_dbh
921 {
922     my $self = shift;
923
924     if ($#{$context->{"dbh_stack"}} < 0)
925     {
926         # Stack underflow
927         die "DBH stack underflow";
928     }
929
930     # Pop the old database handle and set it.
931     $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
932
933     # FIXME - If it is determined that restore_context should
934     # return something, then this function should, too.
935 }
936
937 =head2 queryparser
938
939   $queryparser = C4::Context->queryparser
940
941 Returns a handle to an initialized Koha::QueryParser::Driver::PQF object.
942
943 =cut
944
945 sub queryparser {
946     my $self = shift;
947     unless (defined $context->{"queryparser"}) {
948         $context->{"queryparser"} = &_new_queryparser();
949     }
950
951     return
952       defined( $context->{"queryparser"} )
953       ? $context->{"queryparser"}->new
954       : undef;
955 }
956
957 =head2 _new_queryparser
958
959 Internal helper function to create a new QueryParser object. QueryParser
960 is loaded dynamically so as to keep the lack of the QueryParser library from
961 getting in anyone's way.
962
963 =cut
964
965 sub _new_queryparser {
966     my $qpmodules = {
967         'OpenILS::QueryParser'           => undef,
968         'Koha::QueryParser::Driver::PQF' => undef
969     };
970     if ( can_load( 'modules' => $qpmodules ) ) {
971         my $QParser     = Koha::QueryParser::Driver::PQF->new();
972         my $config_file = $context->config('queryparser_config');
973         $config_file ||= '/etc/koha/searchengine/queryparser.yaml';
974         if ( $QParser->load_config($config_file) ) {
975             # Set 'keyword' as the default search class
976             $QParser->default_search_class('keyword');
977             # TODO: allow indexes to be configured in the database
978             return $QParser;
979         }
980     }
981     return;
982 }
983
984 =head2 marcfromkohafield
985
986   $dbh = C4::Context->marcfromkohafield;
987
988 Returns a hash with marcfromkohafield.
989
990 This hash is cached for future use: if you call
991 C<C4::Context-E<gt>marcfromkohafield> twice, you will get the same hash without real DB access
992
993 =cut
994
995 #'
996 sub marcfromkohafield
997 {
998     my $retval = {};
999
1000     # If the hash already exists, return it.
1001     return $context->{"marcfromkohafield"} if defined($context->{"marcfromkohafield"});
1002
1003     # No hash. Create one.
1004     $context->{"marcfromkohafield"} = &_new_marcfromkohafield();
1005
1006     return $context->{"marcfromkohafield"};
1007 }
1008
1009 # _new_marcfromkohafield
1010 # Internal helper function (not a method!). This creates a new
1011 # hash with stopwords
1012 sub _new_marcfromkohafield
1013 {
1014     my $dbh = C4::Context->dbh;
1015     my $marcfromkohafield;
1016     my $sth = $dbh->prepare("select frameworkcode,kohafield,tagfield,tagsubfield from marc_subfield_structure where kohafield > ''");
1017     $sth->execute;
1018     while (my ($frameworkcode,$kohafield,$tagfield,$tagsubfield) = $sth->fetchrow) {
1019         my $retval = {};
1020         $marcfromkohafield->{$frameworkcode}->{$kohafield} = [$tagfield,$tagsubfield];
1021     }
1022     return $marcfromkohafield;
1023 }
1024
1025 =head2 stopwords
1026
1027   $dbh = C4::Context->stopwords;
1028
1029 Returns a hash with stopwords.
1030
1031 This hash is cached for future use: if you call
1032 C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
1033
1034 =cut
1035
1036 #'
1037 sub stopwords
1038 {
1039     my $retval = {};
1040
1041     # If the hash already exists, return it.
1042     return $context->{"stopwords"} if defined($context->{"stopwords"});
1043
1044     # No hash. Create one.
1045     $context->{"stopwords"} = &_new_stopwords();
1046
1047     return $context->{"stopwords"};
1048 }
1049
1050 # _new_stopwords
1051 # Internal helper function (not a method!). This creates a new
1052 # hash with stopwords
1053 sub _new_stopwords
1054 {
1055     my $dbh = C4::Context->dbh;
1056     my $stopwordlist;
1057     my $sth = $dbh->prepare("select word from stopwords");
1058     $sth->execute;
1059     while (my $stopword = $sth->fetchrow_array) {
1060         $stopwordlist->{$stopword} = uc($stopword);
1061     }
1062     $stopwordlist->{A} = "A" unless $stopwordlist;
1063     return $stopwordlist;
1064 }
1065
1066 =head2 userenv
1067
1068   C4::Context->userenv;
1069
1070 Retrieves a hash for user environment variables.
1071
1072 This hash shall be cached for future use: if you call
1073 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
1074
1075 =cut
1076
1077 #'
1078 sub userenv {
1079     my $var = $context->{"activeuser"};
1080     if (defined $var and defined $context->{"userenv"}->{$var}) {
1081         return $context->{"userenv"}->{$var};
1082     } else {
1083         return;
1084     }
1085 }
1086
1087 =head2 set_userenv
1088
1089   C4::Context->set_userenv($usernum, $userid, $usercnum, $userfirstname, 
1090                   $usersurname, $userbranch, $userflags, $emailaddress, $branchprinter,
1091                   $persona);
1092
1093 Establish a hash of user environment variables.
1094
1095 set_userenv is called in Auth.pm
1096
1097 =cut
1098
1099 #'
1100 sub set_userenv {
1101     my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter, $persona, $shibboleth)=
1102     map { Encode::is_utf8( $_ ) ? $_ : Encode::decode('UTF-8', $_) } # CGI::Session doesn't handle utf-8, so we decode it here
1103     @_;
1104     my $var=$context->{"activeuser"} || '';
1105     my $cell = {
1106         "number"     => $usernum,
1107         "id"         => $userid,
1108         "cardnumber" => $usercnum,
1109         "firstname"  => $userfirstname,
1110         "surname"    => $usersurname,
1111         #possibly a law problem
1112         "branch"     => $userbranch,
1113         "branchname" => $branchname,
1114         "flags"      => $userflags,
1115         "emailaddress"     => $emailaddress,
1116         "branchprinter"    => $branchprinter,
1117         "persona"    => $persona,
1118         "shibboleth" => $shibboleth,
1119     };
1120     $context->{userenv}->{$var} = $cell;
1121     return $cell;
1122 }
1123
1124 sub set_shelves_userenv {
1125         my ($type, $shelves) = @_ or return;
1126         my $activeuser = $context->{activeuser} or return;
1127         $context->{userenv}->{$activeuser}->{barshelves} = $shelves if $type eq 'bar';
1128         $context->{userenv}->{$activeuser}->{pubshelves} = $shelves if $type eq 'pub';
1129         $context->{userenv}->{$activeuser}->{totshelves} = $shelves if $type eq 'tot';
1130 }
1131
1132 sub get_shelves_userenv {
1133         my $active;
1134         unless ($active = $context->{userenv}->{$context->{activeuser}}) {
1135                 $debug and warn "get_shelves_userenv cannot retrieve context->{userenv}->{context->{activeuser}}";
1136                 return;
1137         }
1138         my $totshelves = $active->{totshelves} or undef;
1139         my $pubshelves = $active->{pubshelves} or undef;
1140         my $barshelves = $active->{barshelves} or undef;
1141         return ($totshelves, $pubshelves, $barshelves);
1142 }
1143
1144 =head2 _new_userenv
1145
1146   C4::Context->_new_userenv($session);  # FIXME: This calling style is wrong for what looks like an _internal function
1147
1148 Builds a hash for user environment variables.
1149
1150 This hash shall be cached for future use: if you call
1151 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
1152
1153 _new_userenv is called in Auth.pm
1154
1155 =cut
1156
1157 #'
1158 sub _new_userenv
1159 {
1160     shift;  # Useless except it compensates for bad calling style
1161     my ($sessionID)= @_;
1162      $context->{"activeuser"}=$sessionID;
1163 }
1164
1165 =head2 _unset_userenv
1166
1167   C4::Context->_unset_userenv;
1168
1169 Destroys the hash for activeuser user environment variables.
1170
1171 =cut
1172
1173 #'
1174
1175 sub _unset_userenv
1176 {
1177     my ($sessionID)= @_;
1178     undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
1179 }
1180
1181
1182 =head2 get_versions
1183
1184   C4::Context->get_versions
1185
1186 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'.
1187
1188 =cut
1189
1190 #'
1191
1192 # A little example sub to show more debugging info for CGI::Carp
1193 sub get_versions {
1194     my %versions;
1195     $versions{kohaVersion}  = KOHAVERSION();
1196     $versions{kohaDbVersion} = C4::Context->preference('version');
1197     $versions{osVersion} = join(" ", POSIX::uname());
1198     $versions{perlVersion} = $];
1199     {
1200         no warnings qw(exec); # suppress warnings if unable to find a program in $PATH
1201         $versions{mysqlVersion}  = `mysql -V`;
1202         $versions{apacheVersion} = `httpd -v`;
1203         $versions{apacheVersion} = `httpd2 -v`            unless  $versions{apacheVersion} ;
1204         $versions{apacheVersion} = `apache2 -v`           unless  $versions{apacheVersion} ;
1205         $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless  $versions{apacheVersion} ;
1206     }
1207     return %versions;
1208 }
1209
1210
1211 =head2 tz
1212
1213   C4::Context->tz
1214
1215   Returns a DateTime::TimeZone object for the system timezone
1216
1217 =cut
1218
1219 sub tz {
1220     my $self = shift;
1221     if (!defined $context->{tz}) {
1222         $context->{tz} = DateTime::TimeZone->new(name => 'local');
1223     }
1224     return $context->{tz};
1225 }
1226
1227
1228 =head2 IsSuperLibrarian
1229
1230     C4::Context->IsSuperlibrarian();
1231
1232 =cut
1233
1234 sub IsSuperLibrarian {
1235     my $userenv = C4::Context->userenv;
1236
1237     unless ( $userenv and exists $userenv->{flags} ) {
1238         # If we reach this without a user environment,
1239         # assume that we're running from a command-line script,
1240         # and act as a superlibrarian.
1241         carp("C4::Context->userenv not defined!");
1242         return 1;
1243     }
1244
1245     return ($userenv->{flags}//0) % 2;
1246 }
1247
1248 =head2 interface
1249
1250 Sets the current interface for later retrieval in any Perl module
1251
1252     C4::Context->interface('opac');
1253     C4::Context->interface('intranet');
1254     my $interface = C4::Context->interface;
1255
1256 =cut
1257
1258 sub interface {
1259     my ($class, $interface) = @_;
1260
1261     if (defined $interface) {
1262         $interface = lc $interface;
1263         if ($interface eq 'opac' || $interface eq 'intranet') {
1264             $context->{interface} = $interface;
1265         } else {
1266             warn "invalid interface : '$interface'";
1267         }
1268     }
1269
1270     return $context->{interface} // 'opac';
1271 }
1272
1273 1;
1274 __END__
1275
1276 =head1 ENVIRONMENT
1277
1278 =head2 C<KOHA_CONF>
1279
1280 Specifies the configuration file to read.
1281
1282 =head1 SEE ALSO
1283
1284 XML::Simple
1285
1286 =head1 AUTHORS
1287
1288 Andrew Arensburger <arensb at ooblick dot com>
1289
1290 Joshua Ferraro <jmf at liblime dot com>
1291