Bug 8798: (follow-up) remove tabs
[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 $ENV{'DBIC_DONT_VALIDATE_RELS'} = 1; # FIXME once the DBIx schema has its schema adjusted we should remove this
23 BEGIN {
24         if ($ENV{'HTTP_USER_AGENT'})    {
25                 require CGI::Carp;
26         # FIXME for future reference, CGI::Carp doc says
27         #  "Note that fatalsToBrowser does not work with mod_perl version 2.0 and higher."
28                 import CGI::Carp qw(fatalsToBrowser);
29                         sub handle_errors {
30                             my $msg = shift;
31                             my $debug_level;
32                             eval {C4::Context->dbh();};
33                             if ($@){
34                                 $debug_level = 1;
35                             } 
36                             else {
37                                 $debug_level =  C4::Context->preference("DebugLevel");
38                             }
39
40                 print q(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
41                             "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
42                        <html lang="en" xml:lang="en"  xmlns="http://www.w3.org/1999/xhtml">
43                        <head><title>Koha Error</title></head>
44                        <body>
45                 );
46                                 if ($debug_level eq "2"){
47                                         # debug 2 , print extra info too.
48                                         my %versions = get_versions();
49
50                 # a little example table with various version info";
51                                         print "
52                                                 <h1>Koha error</h1>
53                                                 <p>The following fatal error has occurred:</p> 
54                         <pre><code>$msg</code></pre>
55                                                 <table>
56                                                 <tr><th>Apache</th><td>  $versions{apacheVersion}</td></tr>
57                                                 <tr><th>Koha</th><td>    $versions{kohaVersion}</td></tr>
58                                                 <tr><th>Koha DB</th><td> $versions{kohaDbVersion}</td></tr>
59                                                 <tr><th>MySQL</th><td>   $versions{mysqlVersion}</td></tr>
60                                                 <tr><th>OS</th><td>      $versions{osVersion}</td></tr>
61                                                 <tr><th>Perl</th><td>    $versions{perlVersion}</td></tr>
62                                                 </table>";
63
64                                 } elsif ($debug_level eq "1"){
65                                         print "
66                                                 <h1>Koha error</h1>
67                                                 <p>The following fatal error has occurred:</p> 
68                         <pre><code>$msg</code></pre>";
69                                 } else {
70                                         print "<p>production mode - trapped fatal error</p>";
71                                 }       
72                 print "</body></html>";
73                         }
74                 #CGI::Carp::set_message(\&handle_errors);
75                 ## give a stack backtrace if KOHA_BACKTRACES is set
76                 ## can't rely on DebugLevel for this, as we're not yet connected
77                 if ($ENV{KOHA_BACKTRACES}) {
78                         $main::SIG{__DIE__} = \&CGI::Carp::confess;
79                 }
80     }   # else there is no browser to send fatals to!
81
82     # Check if there are memcached servers set
83     $servers = $ENV{'MEMCACHED_SERVERS'};
84     if ($servers) {
85         # Load required libraries and create the memcached object
86         require Cache::Memcached;
87         $memcached = Cache::Memcached->new({
88         servers => [ $servers ],
89         debug   => 0,
90         compress_threshold => 10_000,
91         expire_time => 600,
92         namespace => $ENV{'MEMCACHED_NAMESPACE'} || 'koha'
93     });
94         # Verify memcached available (set a variable and test the output)
95     $ismemcached = $memcached->set('ismemcached','1');
96     }
97
98     $VERSION = '3.07.00.049';
99 }
100
101 use DBI;
102 require Koha::Schema;
103 use ZOOM;
104 use XML::Simple;
105 use C4::Boolean;
106 use C4::Debug;
107 use POSIX ();
108 use DateTime::TimeZone;
109 use Module::Load::Conditional qw(can_load);
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 # db_scheme2dbi
298 # Translates the full text name of a database into de appropiate dbi name
299
300 sub db_scheme2dbi {
301     my $name = shift;
302     # for instance, we support only mysql, so don't care checking
303     return "mysql";
304     for ($name) {
305 # FIXME - Should have other databases. 
306         if (/mysql/) { return("mysql"); }
307         if (/Postgres|Pg|PostgresSQL/) { return("Pg"); }
308         if (/oracle/) { return("Oracle"); }
309     }
310     return;         # Just in case
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     return $self;
406 }
407
408 =head2 set_context
409
410   $context = new C4::Context;
411   $context->set_context();
412 or
413   set_context C4::Context $context;
414
415   ...
416   restore_context C4::Context;
417
418 In some cases, it might be necessary for a script to use multiple
419 contexts. C<&set_context> saves the current context on a stack, then
420 sets the context to C<$context>, which will be used in future
421 operations. To restore the previous context, use C<&restore_context>.
422
423 =cut
424
425 #'
426 sub set_context
427 {
428     my $self = shift;
429     my $new_context;    # The context to set
430
431     # Figure out whether this is a class or instance method call.
432     #
433     # We're going to make the assumption that control got here
434     # through valid means, i.e., that the caller used an instance
435     # or class method call, and that control got here through the
436     # usual inheritance mechanisms. The caller can, of course,
437     # break this assumption by playing silly buggers, but that's
438     # harder to do than doing it properly, and harder to check
439     # for.
440     if (ref($self) eq "")
441     {
442         # Class method. The new context is the next argument.
443         $new_context = shift;
444     } else {
445         # Instance method. The new context is $self.
446         $new_context = $self;
447     }
448
449     # Save the old context, if any, on the stack
450     push @context_stack, $context if defined($context);
451
452     # Set the new context
453     $context = $new_context;
454 }
455
456 =head2 restore_context
457
458   &restore_context;
459
460 Restores the context set by C<&set_context>.
461
462 =cut
463
464 #'
465 sub restore_context
466 {
467     my $self = shift;
468
469     if ($#context_stack < 0)
470     {
471         # Stack underflow.
472         die "Context stack underflow";
473     }
474
475     # Pop the old context and set it.
476     $context = pop @context_stack;
477
478     # FIXME - Should this return something, like maybe the context
479     # that was current when this was called?
480 }
481
482 =head2 config
483
484   $value = C4::Context->config("config_variable");
485
486   $value = C4::Context->config_variable;
487
488 Returns the value of a variable specified in the configuration file
489 from which the current context was created.
490
491 The second form is more compact, but of course may conflict with
492 method names. If there is a configuration variable called "new", then
493 C<C4::Config-E<gt>new> will not return it.
494
495 =cut
496
497 sub _common_config {
498         my $var = shift;
499         my $term = shift;
500     return if !defined($context->{$term});
501        # Presumably $self->{$term} might be
502        # undefined if the config file given to &new
503        # didn't exist, and the caller didn't bother
504        # to check the return value.
505
506     # Return the value of the requested config variable
507     return $context->{$term}->{$var};
508 }
509
510 sub config {
511         return _common_config($_[1],'config');
512 }
513 sub zebraconfig {
514         return _common_config($_[1],'server');
515 }
516 sub ModZebrations {
517         return _common_config($_[1],'serverinfo');
518 }
519
520 =head2 preference
521
522   $sys_preference = C4::Context->preference('some_variable');
523
524 Looks up the value of the given system preference in the
525 systempreferences table of the Koha database, and returns it. If the
526 variable is not set or does not exist, undef is returned.
527
528 In case of an error, this may return 0.
529
530 Note: It is impossible to tell the difference between system
531 preferences which do not exist, and those whose values are set to NULL
532 with this method.
533
534 =cut
535
536 # FIXME: running this under mod_perl will require a means of
537 # flushing the caching mechanism.
538
539 my %sysprefs;
540 my $use_syspref_cache = 1;
541
542 sub preference {
543     my $self = shift;
544     my $var  = shift;    # The system preference to return
545
546     if ($use_syspref_cache && exists $sysprefs{lc $var}) {
547         return $sysprefs{lc $var};
548     }
549
550     my $dbh  = C4::Context->dbh or return 0;
551
552     my $value;
553     if ( defined $ENV{"OVERRIDE_SYSPREF_$var"} ) {
554         $value = $ENV{"OVERRIDE_SYSPREF_$var"};
555     } else {
556         # Look up systempreferences.variable==$var
557         my $sql = q{
558             SELECT  value
559             FROM    systempreferences
560             WHERE   variable = ?
561             LIMIT   1
562         };
563         $value = $dbh->selectrow_array( $sql, {}, lc $var );
564     }
565
566     $sysprefs{lc $var} = $value;
567     return $value;
568 }
569
570 sub boolean_preference {
571     my $self = shift;
572     my $var = shift;        # The system preference to return
573     my $it = preference($self, $var);
574     return defined($it)? C4::Boolean::true_p($it): undef;
575 }
576
577 =head2 enable_syspref_cache
578
579   C4::Context->enable_syspref_cache();
580
581 Enable the in-memory syspref cache used by C4::Context. This is the
582 default behavior.
583
584 =cut
585
586 sub enable_syspref_cache {
587     my ($self) = @_;
588     $use_syspref_cache = 1;
589 }
590
591 =head2 disable_syspref_cache
592
593   C4::Context->disable_syspref_cache();
594
595 Disable the in-memory syspref cache used by C4::Context. This should be
596 used with Plack and other persistent environments.
597
598 =cut
599
600 sub disable_syspref_cache {
601     my ($self) = @_;
602     $use_syspref_cache = 0;
603     $self->clear_syspref_cache();
604 }
605
606 =head2 clear_syspref_cache
607
608   C4::Context->clear_syspref_cache();
609
610 cleans the internal cache of sysprefs. Please call this method if
611 you update the systempreferences table. Otherwise, your new changes
612 will not be seen by this process.
613
614 =cut
615
616 sub clear_syspref_cache {
617     %sysprefs = ();
618 }
619
620 =head2 set_preference
621
622   C4::Context->set_preference( $variable, $value );
623
624 This updates a preference's value both in the systempreferences table and in
625 the sysprefs cache.
626
627 =cut
628
629 sub set_preference {
630     my $self = shift;
631     my $var = lc(shift);
632     my $value = shift;
633
634     my $dbh = C4::Context->dbh or return 0;
635
636     my $type = $dbh->selectrow_array( "SELECT type FROM systempreferences WHERE variable = ?", {}, $var );
637
638     $value = 0 if ( $type && $type eq 'YesNo' && $value eq '' );
639
640     my $sth = $dbh->prepare( "
641       INSERT INTO systempreferences
642         ( variable, value )
643         VALUES( ?, ? )
644         ON DUPLICATE KEY UPDATE value = VALUES(value)
645     " );
646
647     if($sth->execute( $var, $value )) {
648         $sysprefs{$var} = $value;
649     }
650     $sth->finish;
651 }
652
653 # AUTOLOAD
654 # This implements C4::Config->foo, and simply returns
655 # C4::Context->config("foo"), as described in the documentation for
656 # &config, above.
657
658 # FIXME - Perhaps this should be extended to check &config first, and
659 # then &preference if that fails. OTOH, AUTOLOAD could lead to crappy
660 # code, so it'd probably be best to delete it altogether so as not to
661 # encourage people to use it.
662 sub AUTOLOAD
663 {
664     my $self = shift;
665
666     $AUTOLOAD =~ s/.*:://;        # Chop off the package name,
667                     # leaving only the function name.
668     return $self->config($AUTOLOAD);
669 }
670
671 =head2 Zconn
672
673   $Zconn = C4::Context->Zconn
674
675 Returns a connection to the Zebra database for the current
676 context. If no connection has yet been made, this method 
677 creates one and connects.
678
679 C<$self> 
680
681 C<$server> one of the servers defined in the koha-conf.xml file
682
683 C<$async> whether this is a asynchronous connection
684
685 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
686
687
688 =cut
689
690 sub Zconn {
691     my $self=shift;
692     my $server=shift;
693     my $async=shift;
694     my $auth=shift;
695     my $piggyback=shift;
696     my $syntax=shift;
697     if ( defined($context->{"Zconn"}->{$server}) && (0 == $context->{"Zconn"}->{$server}->errcode()) ) {
698         return $context->{"Zconn"}->{$server};
699     # No connection object or it died. Create one.
700     }else {
701         # release resources if we're closing a connection and making a new one
702         # FIXME: this needs to be smarter -- an error due to a malformed query or
703         # a missing index does not necessarily require us to close the connection
704         # and make a new one, particularly for a batch job.  However, at
705         # first glance it does not look like there's a way to easily check
706         # the basic health of a ZOOM::Connection
707         $context->{"Zconn"}->{$server}->destroy() if defined($context->{"Zconn"}->{$server});
708
709         $context->{"Zconn"}->{$server} = &_new_Zconn($server,$async,$auth,$piggyback,$syntax);
710         $context->{ Zconn }->{ $server }->option(
711             preferredRecordSyntax => C4::Context->preference("marcflavour") );
712         return $context->{"Zconn"}->{$server};
713     }
714 }
715
716 =head2 _new_Zconn
717
718 $context->{"Zconn"} = &_new_Zconn($server,$async);
719
720 Internal function. Creates a new database connection from the data given in the current context and returns it.
721
722 C<$server> one of the servers defined in the koha-conf.xml file
723
724 C<$async> whether this is a asynchronous connection
725
726 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
727
728 =cut
729
730 sub _new_Zconn {
731     my ($server,$async,$auth,$piggyback,$syntax) = @_;
732
733     my $tried=0; # first attempt
734     my $Zconn; # connection object
735     $server = "biblioserver" unless $server;
736     $syntax = "usmarc" unless $syntax;
737
738     my $host = $context->{'listen'}->{$server}->{'content'};
739     my $servername = $context->{"config"}->{$server};
740     my $user = $context->{"serverinfo"}->{$server}->{"user"};
741     my $password = $context->{"serverinfo"}->{$server}->{"password"};
742  $auth = 1 if($user && $password);   
743     retry:
744     eval {
745         # set options
746         my $o = new ZOOM::Options();
747         $o->option(user=>$user) if $auth;
748         $o->option(password=>$password) if $auth;
749         $o->option(async => 1) if $async;
750         $o->option(count => $piggyback) if $piggyback;
751         $o->option(cqlfile=> $context->{"server"}->{$server}->{"cql2rpn"});
752         $o->option(cclfile=> $context->{"serverinfo"}->{$server}->{"ccl2rpn"});
753         $o->option(preferredRecordSyntax => $syntax);
754         $o->option(elementSetName => "F"); # F for 'full' as opposed to B for 'brief'
755         $o->option(databaseName => ($servername?$servername:"biblios"));
756
757         # create a new connection object
758         $Zconn= create ZOOM::Connection($o);
759
760         # forge to server
761         $Zconn->connect($host, 0);
762
763         # check for errors and warn
764         if ($Zconn->errcode() !=0) {
765             warn "something wrong with the connection: ". $Zconn->errmsg();
766         }
767
768     };
769 #     if ($@) {
770 #         # Koha manages the Zebra server -- this doesn't work currently for me because of permissions issues
771 #         # Also, I'm skeptical about whether it's the best approach
772 #         warn "problem with Zebra";
773 #         if ( C4::Context->preference("ManageZebra") ) {
774 #             if ($@->code==10000 && $tried==0) { ##No connection try restarting Zebra
775 #                 $tried=1;
776 #                 warn "trying to restart Zebra";
777 #                 my $res=system("zebrasrv -f $ENV{'KOHA_CONF'} >/koha/log/zebra-error.log");
778 #                 goto "retry";
779 #             } else {
780 #                 warn "Error ", $@->code(), ": ", $@->message(), "\n";
781 #                 $Zconn="error";
782 #                 return $Zconn;
783 #             }
784 #         }
785 #     }
786     return $Zconn;
787 }
788
789 # _new_dbh
790 # Internal helper function (not a method!). This creates a new
791 # database connection from the data given in the current context, and
792 # returns it.
793 sub _new_dbh
794 {
795
796     ## $context
797     ## correct name for db_schme        
798     my $db_driver;
799     if ($context->config("db_scheme")){
800         $db_driver=db_scheme2dbi($context->config("db_scheme"));
801     }else{
802         $db_driver="mysql";
803     }
804
805     my $db_name   = $context->config("database");
806     my $db_host   = $context->config("hostname");
807     my $db_port   = $context->config("port") || '';
808     my $db_user   = $context->config("user");
809     my $db_passwd = $context->config("pass");
810     # MJR added or die here, as we can't work without dbh
811     my $dbh = DBI->connect("DBI:$db_driver:dbname=$db_name;host=$db_host;port=$db_port",
812     $db_user, $db_passwd, {'RaiseError' => $ENV{DEBUG}?1:0 }) or die $DBI::errstr;
813
814     # Check for the existence of a systempreference table; if we don't have this, we don't
815     # have a valid database and should not set RaiseError in order to allow the installer
816     # to run; installer will not run otherwise since we raise all db errors
817
818     eval {
819                 local $dbh->{PrintError} = 0;
820                 local $dbh->{RaiseError} = 1;
821                 $dbh->do(qq{SELECT * FROM systempreferences WHERE 1 = 0 });
822     };
823
824     if ($@) {
825         $dbh->{RaiseError} = 0;
826     }
827
828         my $tz = $ENV{TZ};
829     if ( $db_driver eq 'mysql' ) { 
830         # Koha 3.0 is utf-8, so force utf8 communication between mySQL and koha, whatever the mysql default config.
831         # this is better than modifying my.cnf (and forcing all communications to be in utf8)
832         $dbh->{'mysql_enable_utf8'}=1; #enable
833         $dbh->do("set NAMES 'utf8'");
834         ($tz) and $dbh->do(qq(SET time_zone = "$tz"));
835     }
836     elsif ( $db_driver eq 'Pg' ) {
837             $dbh->do( "set client_encoding = 'UTF8';" );
838         ($tz) and $dbh->do(qq(SET TIME ZONE = "$tz"));
839     }
840     return $dbh;
841 }
842
843 =head2 dbh
844
845   $dbh = C4::Context->dbh;
846
847 Returns a database handle connected to the Koha database for the
848 current context. If no connection has yet been made, this method
849 creates one, and connects to the database.
850
851 This database handle is cached for future use: if you call
852 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
853 times. If you need a second database handle, use C<&new_dbh> and
854 possibly C<&set_dbh>.
855
856 =cut
857
858 #'
859 sub dbh
860 {
861     my $self = shift;
862     my $sth;
863
864     if (defined($context->{"dbh"}) && $context->{"dbh"}->ping()) {
865         return $context->{"dbh"};
866     }
867
868     # No database handle or it died . Create one.
869     $context->{"dbh"} = &_new_dbh();
870
871     return $context->{"dbh"};
872 }
873
874 =head2 new_dbh
875
876   $dbh = C4::Context->new_dbh;
877
878 Creates a new connection to the Koha database for the current context,
879 and returns the database handle (a C<DBI::db> object).
880
881 The handle is not saved anywhere: this method is strictly a
882 convenience function; the point is that it knows which database to
883 connect to so that the caller doesn't have to know.
884
885 =cut
886
887 #'
888 sub new_dbh
889 {
890     my $self = shift;
891
892     return &_new_dbh();
893 }
894
895 =head2 set_dbh
896
897   $my_dbh = C4::Connect->new_dbh;
898   C4::Connect->set_dbh($my_dbh);
899   ...
900   C4::Connect->restore_dbh;
901
902 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
903 C<&set_context> and C<&restore_context>.
904
905 C<&set_dbh> saves the current database handle on a stack, then sets
906 the current database handle to C<$my_dbh>.
907
908 C<$my_dbh> is assumed to be a good database handle.
909
910 =cut
911
912 #'
913 sub set_dbh
914 {
915     my $self = shift;
916     my $new_dbh = shift;
917
918     # Save the current database handle on the handle stack.
919     # We assume that $new_dbh is all good: if the caller wants to
920     # screw himself by passing an invalid handle, that's fine by
921     # us.
922     push @{$context->{"dbh_stack"}}, $context->{"dbh"};
923     $context->{"dbh"} = $new_dbh;
924 }
925
926 =head2 restore_dbh
927
928   C4::Context->restore_dbh;
929
930 Restores the database handle saved by an earlier call to
931 C<C4::Context-E<gt>set_dbh>.
932
933 =cut
934
935 #'
936 sub restore_dbh
937 {
938     my $self = shift;
939
940     if ($#{$context->{"dbh_stack"}} < 0)
941     {
942         # Stack underflow
943         die "DBH stack underflow";
944     }
945
946     # Pop the old database handle and set it.
947     $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
948
949     # FIXME - If it is determined that restore_context should
950     # return something, then this function should, too.
951 }
952
953 =head2 queryparser
954
955   $queryparser = C4::Context->queryparser
956
957 Returns a handle to an initialized Koha::QueryParser::Driver::PQF object.
958
959 =cut
960
961 sub queryparser {
962     my $self = shift;
963     unless (defined $context->{"queryparser"}) {
964         $context->{"queryparser"} = &_new_queryparser();
965     }
966
967     return
968       defined( $context->{"queryparser"} )
969       ? $context->{"queryparser"}->new
970       : undef;
971 }
972
973 =head2 _new_queryparser
974
975 Internal helper function to create a new QueryParser object. QueryParser
976 is loaded dynamically so as to keep the lack of the QueryParser library from
977 getting in anyone's way.
978
979 =cut
980
981 sub _new_queryparser {
982     my $qpmodules = {
983         'OpenILS::QueryParser'           => undef,
984         'Koha::QueryParser::Driver::PQF' => undef
985     };
986     if ( can_load( 'modules' => $qpmodules ) ) {
987         my $QParser     = Koha::QueryParser::Driver::PQF->new();
988         my $config_file = $context->config('queryparser_config');
989         $config_file ||= '/etc/koha/searchengine/queryparser.yaml';
990         if ( $QParser->load_config($config_file) ) {
991             # TODO: allow indexes to be configured in the database
992             return $QParser;
993         }
994     }
995     return;
996 }
997
998 # _new_schema
999 # Internal helper function (not a method!). This creates a new
1000 # database connection from the data given in the current context, and
1001 # returns it.
1002 sub _new_schema {
1003     my $db_driver;
1004     if ($context->config("db_scheme")){
1005         $db_driver=db_scheme2dbi($context->config("db_scheme"));
1006     }else{
1007         $db_driver="mysql";
1008     }
1009
1010     my $db_name   = $context->config("database");
1011     my $db_host   = $context->config("hostname");
1012     my $db_port   = $context->config("port") || '';
1013     my $db_user   = $context->config("user");
1014     my $db_passwd = $context->config("pass");
1015     my $schema = Koha::Schema->connect(
1016         "DBI:$db_driver:dbname=$db_name;host=$db_host;port=$db_port",
1017         $db_user, $db_passwd );
1018     return $schema;
1019 }
1020
1021 =head2 schema
1022
1023     $schema = C4::Context->schema;
1024
1025 Returns a database handle connected to the Koha database for the
1026 current context. If no connection has yet been made, this method
1027 creates one, and connects to the database.
1028
1029 This database handle is cached for future use: if you call
1030 C<C4::Context-E<gt>schema> twice, you will get the same handle both
1031 times. If you need a second database handle, use C<&new_schema> and
1032 possibly C<&set_schema>.
1033
1034 =cut
1035
1036 sub schema {
1037     my $self = shift;
1038     my $sth;
1039
1040     if ( defined( $context->{"schema"} ) && $context->{"schema"}->ping() ) {
1041         return $context->{"schema"};
1042     }
1043
1044     # No database handle or it died . Create one.
1045     $context->{"schema"} = &_new_schema();
1046
1047     return $context->{"schema"};
1048 }
1049
1050 =head2 new_schema
1051
1052   $schema = C4::Context->new_schema;
1053
1054 Creates a new connection to the Koha database for the current context,
1055 and returns the database handle (a C<DBI::db> object).
1056
1057 The handle is not saved anywhere: this method is strictly a
1058 convenience function; the point is that it knows which database to
1059 connect to so that the caller doesn't have to know.
1060
1061 =cut
1062
1063 #'
1064 sub new_schema {
1065     my $self = shift;
1066
1067     return &_new_schema();
1068 }
1069
1070 =head2 set_schema
1071
1072   $my_schema = C4::Connect->new_schema;
1073   C4::Connect->set_schema($my_schema);
1074   ...
1075   C4::Connect->restore_schema;
1076
1077 C<&set_schema> and C<&restore_schema> work in a manner analogous to
1078 C<&set_context> and C<&restore_context>.
1079
1080 C<&set_schema> saves the current database handle on a stack, then sets
1081 the current database handle to C<$my_schema>.
1082
1083 C<$my_schema> is assumed to be a good database handle.
1084
1085 =cut
1086
1087 sub set_schema {
1088     my $self = shift;
1089     my $new_schema = shift;
1090
1091     # Save the current database handle on the handle stack.
1092     # We assume that $new_schema is all good: if the caller wants to
1093     # screw himself by passing an invalid handle, that's fine by
1094     # us.
1095     push @{$context->{"schema_stack"}}, $context->{"schema"};
1096     $context->{"schema"} = $new_schema;
1097 }
1098
1099 =head2 restore_schema
1100
1101   C4::Context->restore_schema;
1102
1103 Restores the database handle saved by an earlier call to
1104 C<C4::Context-E<gt>set_schema>.
1105
1106 =cut
1107
1108 sub restore_schema {
1109     my $self = shift;
1110
1111     if ($#{$context->{"schema_stack"}} < 0) {
1112         # Stack underflow
1113         die "SCHEMA stack underflow";
1114     }
1115
1116     # Pop the old database handle and set it.
1117     $context->{"schema"} = pop @{$context->{"schema_stack"}};
1118
1119     # FIXME - If it is determined that restore_context should
1120     # return something, then this function should, too.
1121 }
1122
1123 =head2 marcfromkohafield
1124
1125   $dbh = C4::Context->marcfromkohafield;
1126
1127 Returns a hash with marcfromkohafield.
1128
1129 This hash is cached for future use: if you call
1130 C<C4::Context-E<gt>marcfromkohafield> twice, you will get the same hash without real DB access
1131
1132 =cut
1133
1134 #'
1135 sub marcfromkohafield
1136 {
1137     my $retval = {};
1138
1139     # If the hash already exists, return it.
1140     return $context->{"marcfromkohafield"} if defined($context->{"marcfromkohafield"});
1141
1142     # No hash. Create one.
1143     $context->{"marcfromkohafield"} = &_new_marcfromkohafield();
1144
1145     return $context->{"marcfromkohafield"};
1146 }
1147
1148 # _new_marcfromkohafield
1149 # Internal helper function (not a method!). This creates a new
1150 # hash with stopwords
1151 sub _new_marcfromkohafield
1152 {
1153     my $dbh = C4::Context->dbh;
1154     my $marcfromkohafield;
1155     my $sth = $dbh->prepare("select frameworkcode,kohafield,tagfield,tagsubfield from marc_subfield_structure where kohafield > ''");
1156     $sth->execute;
1157     while (my ($frameworkcode,$kohafield,$tagfield,$tagsubfield) = $sth->fetchrow) {
1158         my $retval = {};
1159         $marcfromkohafield->{$frameworkcode}->{$kohafield} = [$tagfield,$tagsubfield];
1160     }
1161     return $marcfromkohafield;
1162 }
1163
1164 =head2 stopwords
1165
1166   $dbh = C4::Context->stopwords;
1167
1168 Returns a hash with stopwords.
1169
1170 This hash is cached for future use: if you call
1171 C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
1172
1173 =cut
1174
1175 #'
1176 sub stopwords
1177 {
1178     my $retval = {};
1179
1180     # If the hash already exists, return it.
1181     return $context->{"stopwords"} if defined($context->{"stopwords"});
1182
1183     # No hash. Create one.
1184     $context->{"stopwords"} = &_new_stopwords();
1185
1186     return $context->{"stopwords"};
1187 }
1188
1189 # _new_stopwords
1190 # Internal helper function (not a method!). This creates a new
1191 # hash with stopwords
1192 sub _new_stopwords
1193 {
1194     my $dbh = C4::Context->dbh;
1195     my $stopwordlist;
1196     my $sth = $dbh->prepare("select word from stopwords");
1197     $sth->execute;
1198     while (my $stopword = $sth->fetchrow_array) {
1199         $stopwordlist->{$stopword} = uc($stopword);
1200     }
1201     $stopwordlist->{A} = "A" unless $stopwordlist;
1202     return $stopwordlist;
1203 }
1204
1205 =head2 userenv
1206
1207   C4::Context->userenv;
1208
1209 Retrieves a hash for user environment variables.
1210
1211 This hash shall be cached for future use: if you call
1212 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
1213
1214 =cut
1215
1216 #'
1217 sub userenv {
1218     my $var = $context->{"activeuser"};
1219     if (defined $var and defined $context->{"userenv"}->{$var}) {
1220         return $context->{"userenv"}->{$var};
1221     } else {
1222         return;
1223     }
1224 }
1225
1226 =head2 set_userenv
1227
1228   C4::Context->set_userenv($usernum, $userid, $usercnum, $userfirstname, 
1229                   $usersurname, $userbranch, $userflags, $emailaddress, $branchprinter,
1230                   $persona);
1231
1232 Establish a hash of user environment variables.
1233
1234 set_userenv is called in Auth.pm
1235
1236 =cut
1237
1238 #'
1239 sub set_userenv {
1240     my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter, $persona)= @_;
1241     my $var=$context->{"activeuser"} || '';
1242     my $cell = {
1243         "number"     => $usernum,
1244         "id"         => $userid,
1245         "cardnumber" => $usercnum,
1246         "firstname"  => $userfirstname,
1247         "surname"    => $usersurname,
1248         #possibly a law problem
1249         "branch"     => $userbranch,
1250         "branchname" => $branchname,
1251         "flags"      => $userflags,
1252         "emailaddress"     => $emailaddress,
1253         "branchprinter"    => $branchprinter,
1254         "persona"    => $persona,
1255     };
1256     $context->{userenv}->{$var} = $cell;
1257     return $cell;
1258 }
1259
1260 sub set_shelves_userenv {
1261         my ($type, $shelves) = @_ or return;
1262         my $activeuser = $context->{activeuser} or return;
1263         $context->{userenv}->{$activeuser}->{barshelves} = $shelves if $type eq 'bar';
1264         $context->{userenv}->{$activeuser}->{pubshelves} = $shelves if $type eq 'pub';
1265         $context->{userenv}->{$activeuser}->{totshelves} = $shelves if $type eq 'tot';
1266 }
1267
1268 sub get_shelves_userenv {
1269         my $active;
1270         unless ($active = $context->{userenv}->{$context->{activeuser}}) {
1271                 $debug and warn "get_shelves_userenv cannot retrieve context->{userenv}->{context->{activeuser}}";
1272                 return;
1273         }
1274         my $totshelves = $active->{totshelves} or undef;
1275         my $pubshelves = $active->{pubshelves} or undef;
1276         my $barshelves = $active->{barshelves} or undef;
1277         return ($totshelves, $pubshelves, $barshelves);
1278 }
1279
1280 =head2 _new_userenv
1281
1282   C4::Context->_new_userenv($session);  # FIXME: This calling style is wrong for what looks like an _internal function
1283
1284 Builds a hash for user environment variables.
1285
1286 This hash shall be cached for future use: if you call
1287 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
1288
1289 _new_userenv is called in Auth.pm
1290
1291 =cut
1292
1293 #'
1294 sub _new_userenv
1295 {
1296     shift;  # Useless except it compensates for bad calling style
1297     my ($sessionID)= @_;
1298      $context->{"activeuser"}=$sessionID;
1299 }
1300
1301 =head2 _unset_userenv
1302
1303   C4::Context->_unset_userenv;
1304
1305 Destroys the hash for activeuser user environment variables.
1306
1307 =cut
1308
1309 #'
1310
1311 sub _unset_userenv
1312 {
1313     my ($sessionID)= @_;
1314     undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
1315 }
1316
1317
1318 =head2 get_versions
1319
1320   C4::Context->get_versions
1321
1322 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'.
1323
1324 =cut
1325
1326 #'
1327
1328 # A little example sub to show more debugging info for CGI::Carp
1329 sub get_versions {
1330     my %versions;
1331     $versions{kohaVersion}  = KOHAVERSION();
1332     $versions{kohaDbVersion} = C4::Context->preference('version');
1333     $versions{osVersion} = join(" ", POSIX::uname());
1334     $versions{perlVersion} = $];
1335     {
1336         no warnings qw(exec); # suppress warnings if unable to find a program in $PATH
1337         $versions{mysqlVersion}  = `mysql -V`;
1338         $versions{apacheVersion} = `httpd -v`;
1339         $versions{apacheVersion} = `httpd2 -v`            unless  $versions{apacheVersion} ;
1340         $versions{apacheVersion} = `apache2 -v`           unless  $versions{apacheVersion} ;
1341         $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless  $versions{apacheVersion} ;
1342     }
1343     return %versions;
1344 }
1345
1346
1347 =head2 tz
1348
1349   C4::Context->tz
1350
1351   Returns a DateTime::TimeZone object for the system timezone
1352
1353 =cut
1354
1355 sub tz {
1356     my $self = shift;
1357     if (!defined $context->{tz}) {
1358         $context->{tz} = DateTime::TimeZone->new(name => 'local');
1359     }
1360     return $context->{tz};
1361 }
1362
1363
1364
1365 1;
1366 __END__
1367
1368 =head1 ENVIRONMENT
1369
1370 =head2 C<KOHA_CONF>
1371
1372 Specifies the configuration file to read.
1373
1374 =head1 SEE ALSO
1375
1376 XML::Simple
1377
1378 =head1 AUTHORS
1379
1380 Andrew Arensburger <arensb at ooblick dot com>
1381
1382 Joshua Ferraro <jmf at liblime dot com>
1383
1384 =cut