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