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