TZ - multiple timezone support
[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 with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 USA
18
19 use strict;
20 use vars qw($VERSION $AUTOLOAD $context @context_stack);
21
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         $VERSION = '3.00.00.036';
81 }
82
83 use DBI;
84 use ZOOM;
85 use XML::Simple;
86 use C4::Boolean;
87 use C4::Debug;
88
89 =head1 NAME
90
91 C4::Context - Maintain and manipulate the context of a Koha script
92
93 =head1 SYNOPSIS
94
95   use C4::Context;
96
97   use C4::Context("/path/to/koha-conf.xml");
98
99   $config_value = C4::Context->config("config_variable");
100
101   $koha_preference = C4::Context->preference("preference");
102
103   $db_handle = C4::Context->dbh;
104
105   $Zconn = C4::Context->Zconn;
106
107   $stopwordhash = C4::Context->stopwords;
108
109 =head1 DESCRIPTION
110
111 When a Koha script runs, it makes use of a certain number of things:
112 configuration settings in F</etc/koha/koha-conf.xml>, a connection to the Koha
113 databases, and so forth. These things make up the I<context> in which
114 the script runs.
115
116 This module takes care of setting up the context for a script:
117 figuring out which configuration file to load, and loading it, opening
118 a connection to the right database, and so forth.
119
120 Most scripts will only use one context. They can simply have
121
122   use C4::Context;
123
124 at the top.
125
126 Other scripts may need to use several contexts. For instance, if a
127 library has two databases, one for a certain collection, and the other
128 for everything else, it might be necessary for a script to use two
129 different contexts to search both databases. Such scripts should use
130 the C<&set_context> and C<&restore_context> functions, below.
131
132 By default, C4::Context reads the configuration from
133 F</etc/koha/koha-conf.xml>. This may be overridden by setting the C<$KOHA_CONF>
134 environment variable to the pathname of a configuration file to use.
135
136 =head1 METHODS
137
138 =over 2
139
140 =cut
141
142 #'
143 # In addition to what is said in the POD above, a Context object is a
144 # reference-to-hash with the following fields:
145 #
146 # config
147 #    A reference-to-hash whose keys and values are the
148 #    configuration variables and values specified in the config
149 #    file (/etc/koha/koha-conf.xml).
150 # dbh
151 #    A handle to the appropriate database for this context.
152 # dbh_stack
153 #    Used by &set_dbh and &restore_dbh to hold other database
154 #    handles for this context.
155 # Zconn
156 #     A connection object for the Zebra server
157
158 # Koha's main configuration file koha-conf.xml
159 # is searched for according to this priority list:
160 #
161 # 1. Path supplied via use C4::Context '/path/to/koha-conf.xml'
162 # 2. Path supplied in KOHA_CONF environment variable.
163 # 3. Path supplied in INSTALLED_CONFIG_FNAME, as long
164 #    as value has changed from its default of 
165 #    '__KOHA_CONF_DIR__/koha-conf.xml', as happens
166 #    when Koha is installed in 'standard' or 'single'
167 #    mode.
168 # 4. Path supplied in CONFIG_FNAME.
169 #
170 # The first entry that refers to a readable file is used.
171
172 use constant CONFIG_FNAME => "/etc/koha/koha-conf.xml";
173                 # Default config file, if none is specified
174                 
175 my $INSTALLED_CONFIG_FNAME = '__KOHA_CONF_DIR__/koha-conf.xml';
176                 # path to config file set by installer
177                 # __KOHA_CONF_DIR__ is set by rewrite-confg.PL
178                 # when Koha is installed in 'standard' or 'single'
179                 # mode.  If Koha was installed in 'dev' mode, 
180                 # __KOHA_CONF_DIR__ is *not* rewritten; instead
181                 # developers should set the KOHA_CONF environment variable 
182
183 $context = undef;        # Initially, no context is set
184 @context_stack = ();        # Initially, no saved contexts
185
186
187 =item KOHAVERSION
188     returns the kohaversion stored in kohaversion.pl file
189
190 =cut
191
192 sub KOHAVERSION {
193     my $cgidir = C4::Context->intranetdir ."/cgi-bin";
194
195     # 2 cases here : on CVS install, $cgidir does not need a /cgi-bin
196     # on a standard install, /cgi-bin need to be added.
197     # test one, then the other
198     # FIXME - is this all really necessary?
199     unless (opendir(DIR, "$cgidir/cataloguing/value_builder")) {
200         $cgidir = C4::Context->intranetdir;
201         closedir(DIR);
202     }
203
204     do $cgidir."/kohaversion.pl" || die "NO $cgidir/kohaversion.pl";
205     return kohaversion();
206 }
207 =item read_config_file
208
209 =over 4
210
211 Reads the specified Koha config file. 
212
213 Returns an object containing the configuration variables. The object's
214 structure is a bit complex to the uninitiated ... take a look at the
215 koha-conf.xml file as well as the XML::Simple documentation for details. Or,
216 here are a few examples that may give you what you need:
217
218 The simple elements nested within the <config> element:
219
220     my $pass = $koha->{'config'}->{'pass'};
221
222 The <listen> elements:
223
224     my $listen = $koha->{'listen'}->{'biblioserver'}->{'content'};
225
226 The elements nested within the <server> element:
227
228     my $ccl2rpn = $koha->{'server'}->{'biblioserver'}->{'cql2rpn'};
229
230 Returns undef in case of error.
231
232 =back
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']);
238     return $koha;                       # Return value: ref-to-hash holding the configuration
239 }
240
241 # db_scheme2dbi
242 # Translates the full text name of a database into de appropiate dbi name
243
244 sub db_scheme2dbi {
245     my $name = shift;
246
247     for ($name) {
248 # FIXME - Should have other databases. 
249         if (/mysql/i) { return("mysql"); }
250         if (/Postgres|Pg|PostgresSQL/) { return("Pg"); }
251         if (/oracle/i) { return("Oracle"); }
252     }
253     return undef;         # Just in case
254 }
255
256 sub import {
257     my $package = shift;
258     my $conf_fname = shift;        # Config file name
259
260     # Create a new context from the given config file name, if
261     # any, then set it as the current context.
262     $context = new C4::Context($conf_fname) unless $context;
263     return undef if !defined($context);
264     $context->set_context;
265 }
266
267 =item new
268
269   $context = new C4::Context;
270   $context = new C4::Context("/path/to/koha-conf.xml");
271
272 Allocates a new context. Initializes the context from the specified
273 file, which defaults to either the file given by the C<$KOHA_CONF>
274 environment variable, or F</etc/koha/koha-conf.xml>.
275
276 C<&new> does not set this context as the new default context; for
277 that, use C<&set_context>.
278
279 =cut
280
281 #'
282 # Revision History:
283 # 2004-08-10 A. Tarallo: Added check if the conf file is not empty
284 sub new {
285     my $class = shift;
286     my $conf_fname = shift;        # Config file to load
287     my $self = {};
288
289     # check that the specified config file exists and is not empty
290     undef $conf_fname unless 
291         (defined $conf_fname && -s $conf_fname);
292     # Figure out a good config file to load if none was specified.
293     if (!defined($conf_fname))
294     {
295         # If the $KOHA_CONF environment variable is set, use
296         # that. Otherwise, use the built-in default.
297         if (exists $ENV{"KOHA_CONF"} and $ENV{'KOHA_CONF'} and -s  $ENV{"KOHA_CONF"}) {
298             $conf_fname = $ENV{"KOHA_CONF"};
299         } elsif ($INSTALLED_CONFIG_FNAME !~ /__KOHA_CONF_DIR/ and -s $INSTALLED_CONFIG_FNAME) {
300             # NOTE: be careful -- don't change __KOHA_CONF_DIR in the above
301             # regex to anything else -- don't want installer to rewrite it
302             $conf_fname = $INSTALLED_CONFIG_FNAME;
303         } elsif (-s CONFIG_FNAME) {
304             $conf_fname = CONFIG_FNAME;
305         } else {
306             warn "unable to locate Koha configuration file koha-conf.xml";
307             return undef;
308         }
309     }
310         # Load the desired config file.
311     $self = read_config_file($conf_fname);
312     $self->{"config_file"} = $conf_fname;
313     
314     warn "read_config_file($conf_fname) returned undef" if !defined($self->{"config"});
315     return undef if !defined($self->{"config"});
316
317     $self->{"dbh"} = undef;        # Database handle
318     $self->{"Zconn"} = undef;    # Zebra Connections
319     $self->{"stopwords"} = undef; # stopwords list
320     $self->{"marcfromkohafield"} = undef; # the hash with relations between koha table fields and MARC field/subfield
321     $self->{"userenv"} = undef;        # User env
322     $self->{"activeuser"} = undef;        # current active user
323     $self->{"shelves"} = undef;
324
325     bless $self, $class;
326     return $self;
327 }
328
329 =item set_context
330
331   $context = new C4::Context;
332   $context->set_context();
333 or
334   set_context C4::Context $context;
335
336   ...
337   restore_context C4::Context;
338
339 In some cases, it might be necessary for a script to use multiple
340 contexts. C<&set_context> saves the current context on a stack, then
341 sets the context to C<$context>, which will be used in future
342 operations. To restore the previous context, use C<&restore_context>.
343
344 =cut
345
346 #'
347 sub set_context
348 {
349     my $self = shift;
350     my $new_context;    # The context to set
351
352     # Figure out whether this is a class or instance method call.
353     #
354     # We're going to make the assumption that control got here
355     # through valid means, i.e., that the caller used an instance
356     # or class method call, and that control got here through the
357     # usual inheritance mechanisms. The caller can, of course,
358     # break this assumption by playing silly buggers, but that's
359     # harder to do than doing it properly, and harder to check
360     # for.
361     if (ref($self) eq "")
362     {
363         # Class method. The new context is the next argument.
364         $new_context = shift;
365     } else {
366         # Instance method. The new context is $self.
367         $new_context = $self;
368     }
369
370     # Save the old context, if any, on the stack
371     push @context_stack, $context if defined($context);
372
373     # Set the new context
374     $context = $new_context;
375 }
376
377 =item restore_context
378
379   &restore_context;
380
381 Restores the context set by C<&set_context>.
382
383 =cut
384
385 #'
386 sub restore_context
387 {
388     my $self = shift;
389
390     if ($#context_stack < 0)
391     {
392         # Stack underflow.
393         die "Context stack underflow";
394     }
395
396     # Pop the old context and set it.
397     $context = pop @context_stack;
398
399     # FIXME - Should this return something, like maybe the context
400     # that was current when this was called?
401 }
402
403 =item config
404
405   $value = C4::Context->config("config_variable");
406
407   $value = C4::Context->config_variable;
408
409 Returns the value of a variable specified in the configuration file
410 from which the current context was created.
411
412 The second form is more compact, but of course may conflict with
413 method names. If there is a configuration variable called "new", then
414 C<C4::Config-E<gt>new> will not return it.
415
416 =cut
417
418 sub _common_config ($$) {
419         my $var = shift;
420         my $term = shift;
421     return undef if !defined($context->{$term});
422        # Presumably $self->{$term} might be
423        # undefined if the config file given to &new
424        # didn't exist, and the caller didn't bother
425        # to check the return value.
426
427     # Return the value of the requested config variable
428     return $context->{$term}->{$var};
429 }
430
431 sub config {
432         return _common_config($_[1],'config');
433 }
434 sub zebraconfig {
435         return _common_config($_[1],'server');
436 }
437 sub ModZebrations {
438         return _common_config($_[1],'serverinfo');
439 }
440
441 =item preference
442
443   $sys_preference = C4::Context->preference('some_variable');
444
445 Looks up the value of the given system preference in the
446 systempreferences table of the Koha database, and returns it. If the
447 variable is not set or does not exist, undef is returned.
448
449 In case of an error, this may return 0.
450
451 Note: It is impossible to tell the difference between system
452 preferences which do not exist, and those whose values are set to NULL
453 with this method.
454
455 =cut
456
457 # FIXME - The preferences aren't likely to change over the lifetime of
458 # the script (and things might break if they did change), so perhaps
459 # this function should cache the results it finds.
460 sub preference {
461     my $self = shift;
462     my $var  = shift;                          # The system preference to return
463     my $dbh  = C4::Context->dbh or return 0;
464
465     # Look up systempreferences.variable==$var
466     my $sql = <<'END_SQL';
467         SELECT    value
468         FROM    systempreferences
469         WHERE    variable=?
470         LIMIT    1
471 END_SQL
472     my $retval = $dbh->selectrow_array( $sql, {}, $var );
473     return $retval;
474 }
475
476 sub boolean_preference ($) {
477     my $self = shift;
478     my $var = shift;        # The system preference to return
479     my $it = preference($self, $var);
480     return defined($it)? C4::Boolean::true_p($it): undef;
481 }
482
483 # AUTOLOAD
484 # This implements C4::Config->foo, and simply returns
485 # C4::Context->config("foo"), as described in the documentation for
486 # &config, above.
487
488 # FIXME - Perhaps this should be extended to check &config first, and
489 # then &preference if that fails. OTOH, AUTOLOAD could lead to crappy
490 # code, so it'd probably be best to delete it altogether so as not to
491 # encourage people to use it.
492 sub AUTOLOAD
493 {
494     my $self = shift;
495
496     $AUTOLOAD =~ s/.*:://;        # Chop off the package name,
497                     # leaving only the function name.
498     return $self->config($AUTOLOAD);
499 }
500
501 =item Zconn
502
503 $Zconn = C4::Context->Zconn
504
505 Returns a connection to the Zebra database for the current
506 context. If no connection has yet been made, this method 
507 creates one and connects.
508
509 C<$self> 
510
511 C<$server> one of the servers defined in the koha-conf.xml file
512
513 C<$async> whether this is a asynchronous connection
514
515 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
516
517
518 =cut
519
520 sub Zconn {
521     my $self=shift;
522     my $server=shift;
523     my $async=shift;
524     my $auth=shift;
525     my $piggyback=shift;
526     my $syntax=shift;
527     if ( defined($context->{"Zconn"}->{$server}) && (0 == $context->{"Zconn"}->{$server}->errcode()) ) {
528         return $context->{"Zconn"}->{$server};
529     # No connection object or it died. Create one.
530     }else {
531         # release resources if we're closing a connection and making a new one
532         # FIXME: this needs to be smarter -- an error due to a malformed query or
533         # a missing index does not necessarily require us to close the connection
534         # and make a new one, particularly for a batch job.  However, at
535         # first glance it does not look like there's a way to easily check
536         # the basic health of a ZOOM::Connection
537         $context->{"Zconn"}->{$server}->destroy() if defined($context->{"Zconn"}->{$server});
538
539         $context->{"Zconn"}->{$server} = &_new_Zconn($server,$async,$auth,$piggyback,$syntax);
540         return $context->{"Zconn"}->{$server};
541     }
542 }
543
544 =item _new_Zconn
545
546 $context->{"Zconn"} = &_new_Zconn($server,$async);
547
548 Internal function. Creates a new database connection from the data given in the current context and returns it.
549
550 C<$server> one of the servers defined in the koha-conf.xml file
551
552 C<$async> whether this is a asynchronous connection
553
554 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
555
556 =cut
557
558 sub _new_Zconn {
559     my ($server,$async,$auth,$piggyback,$syntax) = @_;
560
561     my $tried=0; # first attempt
562     my $Zconn; # connection object
563     $server = "biblioserver" unless $server;
564     $syntax = "usmarc" unless $syntax;
565
566     my $host = $context->{'listen'}->{$server}->{'content'};
567     my $servername = $context->{"config"}->{$server};
568     my $user = $context->{"serverinfo"}->{$server}->{"user"};
569     my $password = $context->{"serverinfo"}->{$server}->{"password"};
570  $auth = 1 if($user && $password);   
571     retry:
572     eval {
573         # set options
574         my $o = new ZOOM::Options();
575         $o->option(user=>$user) if $auth;
576         $o->option(password=>$password) if $auth;
577         $o->option(async => 1) if $async;
578         $o->option(count => $piggyback) if $piggyback;
579         $o->option(cqlfile=> $context->{"server"}->{$server}->{"cql2rpn"});
580         $o->option(cclfile=> $context->{"serverinfo"}->{$server}->{"ccl2rpn"});
581         $o->option(preferredRecordSyntax => $syntax);
582         $o->option(elementSetName => "F"); # F for 'full' as opposed to B for 'brief'
583         $o->option(databaseName => ($servername?$servername:"biblios"));
584
585         # create a new connection object
586         $Zconn= create ZOOM::Connection($o);
587
588         # forge to server
589         $Zconn->connect($host, 0);
590
591         # check for errors and warn
592         if ($Zconn->errcode() !=0) {
593             warn "something wrong with the connection: ". $Zconn->errmsg();
594         }
595
596     };
597 #     if ($@) {
598 #         # Koha manages the Zebra server -- this doesn't work currently for me because of permissions issues
599 #         # Also, I'm skeptical about whether it's the best approach
600 #         warn "problem with Zebra";
601 #         if ( C4::Context->preference("ManageZebra") ) {
602 #             if ($@->code==10000 && $tried==0) { ##No connection try restarting Zebra
603 #                 $tried=1;
604 #                 warn "trying to restart Zebra";
605 #                 my $res=system("zebrasrv -f $ENV{'KOHA_CONF'} >/koha/log/zebra-error.log");
606 #                 goto "retry";
607 #             } else {
608 #                 warn "Error ", $@->code(), ": ", $@->message(), "\n";
609 #                 $Zconn="error";
610 #                 return $Zconn;
611 #             }
612 #         }
613 #     }
614     return $Zconn;
615 }
616
617 # _new_dbh
618 # Internal helper function (not a method!). This creates a new
619 # database connection from the data given in the current context, and
620 # returns it.
621 sub _new_dbh
622 {
623
624 ### $context
625     ##correct name for db_schme        
626     my $db_driver;
627     if ($context->config("db_scheme")){
628     $db_driver=db_scheme2dbi($context->config("db_scheme"));
629     }else{
630     $db_driver="mysql";
631     }
632
633     my $db_name   = $context->config("database");
634     my $db_host   = $context->config("hostname");
635     my $db_port   = $context->config("port") || '';
636     my $db_user   = $context->config("user");
637     my $db_passwd = $context->config("pass");
638     # MJR added or die here, as we can't work without dbh
639     my $dbh= DBI->connect("DBI:$db_driver:dbname=$db_name;host=$db_host;port=$db_port",
640         $db_user, $db_passwd) or die $DBI::errstr;
641         my $tz = $ENV{TZ};
642     if ( $db_driver eq 'mysql' ) { 
643         # Koha 3.0 is utf-8, so force utf8 communication between mySQL and koha, whatever the mysql default config.
644         # this is better than modifying my.cnf (and forcing all communications to be in utf8)
645         $dbh->{'mysql_enable_utf8'}=1; #enable
646         $dbh->do("set NAMES 'utf8'");
647         ($tz) and $dbh->do(qq(SET time_zone = "$tz"));
648     }
649     elsif ( $db_driver eq 'Pg' ) {
650             $dbh->do( "set client_encoding = 'UTF8';" );
651         ($tz) and $dbh->do(qq(SET TIME ZONE = "$tz"));
652     }
653     return $dbh;
654 }
655
656 =item dbh
657
658   $dbh = C4::Context->dbh;
659
660 Returns a database handle connected to the Koha database for the
661 current context. If no connection has yet been made, this method
662 creates one, and connects to the database.
663
664 This database handle is cached for future use: if you call
665 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
666 times. If you need a second database handle, use C<&new_dbh> and
667 possibly C<&set_dbh>.
668
669 =cut
670
671 #'
672 sub dbh
673 {
674     my $self = shift;
675     my $sth;
676
677     if (defined($context->{"dbh"})) {
678         $sth=$context->{"dbh"}->prepare("select 1");
679         return $context->{"dbh"} if (defined($sth->execute));
680     }
681
682     # No database handle or it died . Create one.
683     $context->{"dbh"} = &_new_dbh();
684
685     return $context->{"dbh"};
686 }
687
688 =item new_dbh
689
690   $dbh = C4::Context->new_dbh;
691
692 Creates a new connection to the Koha database for the current context,
693 and returns the database handle (a C<DBI::db> object).
694
695 The handle is not saved anywhere: this method is strictly a
696 convenience function; the point is that it knows which database to
697 connect to so that the caller doesn't have to know.
698
699 =cut
700
701 #'
702 sub new_dbh
703 {
704     my $self = shift;
705
706     return &_new_dbh();
707 }
708
709 =item set_dbh
710
711   $my_dbh = C4::Connect->new_dbh;
712   C4::Connect->set_dbh($my_dbh);
713   ...
714   C4::Connect->restore_dbh;
715
716 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
717 C<&set_context> and C<&restore_context>.
718
719 C<&set_dbh> saves the current database handle on a stack, then sets
720 the current database handle to C<$my_dbh>.
721
722 C<$my_dbh> is assumed to be a good database handle.
723
724 =cut
725
726 #'
727 sub set_dbh
728 {
729     my $self = shift;
730     my $new_dbh = shift;
731
732     # Save the current database handle on the handle stack.
733     # We assume that $new_dbh is all good: if the caller wants to
734     # screw himself by passing an invalid handle, that's fine by
735     # us.
736     push @{$context->{"dbh_stack"}}, $context->{"dbh"};
737     $context->{"dbh"} = $new_dbh;
738 }
739
740 =item restore_dbh
741
742   C4::Context->restore_dbh;
743
744 Restores the database handle saved by an earlier call to
745 C<C4::Context-E<gt>set_dbh>.
746
747 =cut
748
749 #'
750 sub restore_dbh
751 {
752     my $self = shift;
753
754     if ($#{$context->{"dbh_stack"}} < 0)
755     {
756         # Stack underflow
757         die "DBH stack underflow";
758     }
759
760     # Pop the old database handle and set it.
761     $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
762
763     # FIXME - If it is determined that restore_context should
764     # return something, then this function should, too.
765 }
766
767 =item marcfromkohafield
768
769   $dbh = C4::Context->marcfromkohafield;
770
771 Returns a hash with marcfromkohafield.
772
773 This hash is cached for future use: if you call
774 C<C4::Context-E<gt>marcfromkohafield> twice, you will get the same hash without real DB access
775
776 =cut
777
778 #'
779 sub marcfromkohafield
780 {
781     my $retval = {};
782
783     # If the hash already exists, return it.
784     return $context->{"marcfromkohafield"} if defined($context->{"marcfromkohafield"});
785
786     # No hash. Create one.
787     $context->{"marcfromkohafield"} = &_new_marcfromkohafield();
788
789     return $context->{"marcfromkohafield"};
790 }
791
792 # _new_marcfromkohafield
793 # Internal helper function (not a method!). This creates a new
794 # hash with stopwords
795 sub _new_marcfromkohafield
796 {
797     my $dbh = C4::Context->dbh;
798     my $marcfromkohafield;
799     my $sth = $dbh->prepare("select frameworkcode,kohafield,tagfield,tagsubfield from marc_subfield_structure where kohafield > ''");
800     $sth->execute;
801     while (my ($frameworkcode,$kohafield,$tagfield,$tagsubfield) = $sth->fetchrow) {
802         my $retval = {};
803         $marcfromkohafield->{$frameworkcode}->{$kohafield} = [$tagfield,$tagsubfield];
804     }
805     return $marcfromkohafield;
806 }
807
808 =item stopwords
809
810   $dbh = C4::Context->stopwords;
811
812 Returns a hash with stopwords.
813
814 This hash is cached for future use: if you call
815 C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
816
817 =cut
818
819 #'
820 sub stopwords
821 {
822     my $retval = {};
823
824     # If the hash already exists, return it.
825     return $context->{"stopwords"} if defined($context->{"stopwords"});
826
827     # No hash. Create one.
828     $context->{"stopwords"} = &_new_stopwords();
829
830     return $context->{"stopwords"};
831 }
832
833 # _new_stopwords
834 # Internal helper function (not a method!). This creates a new
835 # hash with stopwords
836 sub _new_stopwords
837 {
838     my $dbh = C4::Context->dbh;
839     my $stopwordlist;
840     my $sth = $dbh->prepare("select word from stopwords");
841     $sth->execute;
842     while (my $stopword = $sth->fetchrow_array) {
843         my $retval = {};
844         $stopwordlist->{$stopword} = uc($stopword);
845     }
846     $stopwordlist->{A} = "A" unless $stopwordlist;
847     return $stopwordlist;
848 }
849
850 =item userenv
851
852   C4::Context->userenv;
853
854 Builds a hash for user environment variables.
855
856 This hash shall be cached for future use: if you call
857 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
858
859 set_userenv is called in Auth.pm
860
861 =cut
862
863 #'
864 sub userenv
865 {
866     my $var = $context->{"activeuser"};
867     return $context->{"userenv"}->{$var} if (defined $context->{"userenv"}->{$var});
868     # insecure=1 management
869     if ($context->{"dbh"} && $context->preference('insecure')) {
870         my %insecure;
871         $insecure{flags} = '16382';
872         $insecure{branchname} ='Insecure';
873         $insecure{number} ='0';
874         $insecure{cardnumber} ='0';
875         $insecure{id} = 'insecure';
876         $insecure{branch} = 'INS';
877         $insecure{emailaddress} = 'test@mode.insecure.com';
878         return \%insecure;
879     } else {
880         return 0;
881     }
882 }
883
884 =item set_userenv
885
886   C4::Context->set_userenv($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $userflags, $emailaddress);
887
888 Informs a hash for user environment variables.
889
890 This hash shall be cached for future use: if you call
891 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
892
893 set_userenv is called in Auth.pm
894
895 =cut
896
897 #'
898 sub set_userenv{
899     my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter)= @_;
900     my $var=$context->{"activeuser"};
901     my $cell = {
902         "number"     => $usernum,
903         "id"         => $userid,
904         "cardnumber" => $usercnum,
905         "firstname"  => $userfirstname,
906         "surname"    => $usersurname,
907 #possibly a law problem
908         "branch"     => $userbranch,
909         "branchname" => $branchname,
910         "flags"      => $userflags,
911         "emailaddress"    => $emailaddress,
912                 "branchprinter"    => $branchprinter
913     };
914     $context->{userenv}->{$var} = $cell;
915     return $cell;
916 }
917
918 sub set_shelves_userenv ($$) {
919         my ($type, $shelves) = @_ or return undef;
920         my $activeuser = $context->{activeuser} or return undef;
921         $context->{userenv}->{$activeuser}->{barshelves} = $shelves if $type eq 'bar';
922         $context->{userenv}->{$activeuser}->{pubshelves} = $shelves if $type eq 'pub';
923         $context->{userenv}->{$activeuser}->{totshelves} = $shelves if $type eq 'tot';
924 }
925
926 sub get_shelves_userenv () {
927         my $active;
928         unless ($active = $context->{userenv}->{$context->{activeuser}}) {
929                 $debug and warn "get_shelves_userenv cannot retrieve context->{userenv}->{context->{activeuser}}";
930                 return undef;
931         }
932         my $totshelves = $active->{totshelves} or undef;
933         my $pubshelves = $active->{pubshelves} or undef;
934         my $barshelves = $active->{barshelves} or undef;
935         return ($totshelves, $pubshelves, $barshelves);
936 }
937
938 =item _new_userenv
939
940   C4::Context->_new_userenv($session);
941
942 Builds a hash for user environment variables.
943
944 This hash shall be cached for future use: if you call
945 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
946
947 _new_userenv is called in Auth.pm
948
949 =cut
950
951 #'
952 sub _new_userenv
953 {
954     shift;
955     my ($sessionID)= @_;
956      $context->{"activeuser"}=$sessionID;
957 }
958
959 =item _unset_userenv
960
961   C4::Context->_unset_userenv;
962
963 Destroys the hash for activeuser user environment variables.
964
965 =cut
966
967 #'
968
969 sub _unset_userenv
970 {
971     my ($sessionID)= @_;
972     undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
973 }
974
975
976 =item get_versions
977
978   C4::Context->get_versions
979
980 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'.
981
982 =cut
983
984 #'
985
986 # A little example sub to show more debugging info for CGI::Carp
987 sub get_versions {
988     my %versions;
989     $versions{kohaVersion}  = KOHAVERSION();
990     $versions{kohaDbVersion} = C4::Context->preference('version');
991     $versions{osVersion} = `uname -a`;
992     $versions{perlVersion} = $];
993     $versions{mysqlVersion} = `mysql -V`;
994     $versions{apacheVersion} =  `httpd -v`;
995     $versions{apacheVersion} =  `httpd2 -v`            unless  $versions{apacheVersion} ;
996     $versions{apacheVersion} =  `apache2 -v`           unless  $versions{apacheVersion} ;
997     $versions{apacheVersion} =  `/usr/sbin/apache2 -v` unless  $versions{apacheVersion} ;
998     return %versions;
999 }
1000
1001
1002 1;
1003 __END__
1004
1005 =back
1006
1007 =head1 ENVIRONMENT
1008
1009 =over 4
1010
1011 =item C<KOHA_CONF>
1012
1013 Specifies the configuration file to read.
1014
1015 =back
1016
1017 =head1 SEE ALSO
1018
1019 XML::Simple
1020
1021 =head1 AUTHORS
1022
1023 Andrew Arensburger <arensb at ooblick dot com>
1024
1025 Joshua Ferraro <jmf at liblime dot com>
1026
1027 =cut
1028
1029 # Revision 1.57  2007/05/22 09:13:55  tipaul
1030 # Bugfixes & improvements (various and minor) :
1031 # - updating templates to have tmpl_process3.pl running without any errors
1032 # - adding a drupal-like css for prog templates (with 3 small images)
1033 # - fixing some bugs in circulation & other scripts
1034 # - updating french translation
1035 # - fixing some typos in templates
1036 #
1037 # Revision 1.56  2007/04/23 15:21:17  tipaul
1038 # renaming currenttransfers to transferstoreceive
1039 #
1040 # Revision 1.55  2007/04/17 08:48:00  tipaul
1041 # circulation cleaning continued: bufixing
1042 #
1043 # Revision 1.54  2007/03/29 16:45:53  tipaul
1044 # Code cleaning of Biblio.pm (continued)
1045 #
1046 # All subs have be cleaned :
1047 # - removed useless
1048 # - merged some
1049 # - reordering Biblio.pm completly
1050 # - using only naming conventions
1051 #
1052 # Seems to have broken nothing, but it still has to be heavily tested.
1053 # Note that Biblio.pm is now much more efficient than previously & probably more reliable as well.
1054 #
1055 # Revision 1.53  2007/03/29 13:30:31  tipaul
1056 # Code cleaning :
1057 # == Biblio.pm cleaning (useless) ==
1058 # * some sub declaration dropped
1059 # * removed modbiblio sub
1060 # * removed moditem sub
1061 # * removed newitems. It was used only in finishrecieve. Replaced by a TransformKohaToMarc+AddItem, that is better.
1062 # * removed MARCkoha2marcItem
1063 # * removed MARCdelsubfield declaration
1064 # * removed MARCkoha2marcBiblio
1065 #
1066 # == Biblio.pm cleaning (naming conventions) ==
1067 # * MARCgettagslib renamed to GetMarcStructure
1068 # * MARCgetitems renamed to GetMarcItem
1069 # * MARCfind_frameworkcode renamed to GetFrameworkCode
1070 # * MARCmarc2koha renamed to TransformMarcToKoha
1071 # * MARChtml2marc renamed to TransformHtmlToMarc
1072 # * MARChtml2xml renamed to TranformeHtmlToXml
1073 # * zebraop renamed to ModZebra
1074 #
1075 # == MARC=OFF ==
1076 # * removing MARC=OFF related scripts (in cataloguing directory)
1077 # * removed checkitems (function related to MARC=off feature, that is completly broken in head. If someone want to reintroduce it, hard work coming...)
1078 # * removed getitemsbybiblioitem (used only by MARC=OFF scripts, that is removed as well)
1079 #
1080 # Revision 1.52  2007/03/16 01:25:08  kados
1081 # Using my precrash CVS copy I did the following:
1082 #
1083 # cvs -z3 -d:ext:kados@cvs.savannah.nongnu.org:/sources/koha co -P koha
1084 # find koha.precrash -type d -name "CVS" -exec rm -v {} \;
1085 # cp -r koha.precrash/* koha/
1086 # cd koha/
1087 # cvs commit
1088 #
1089 # This should in theory put us right back where we were before the crash
1090 #
1091 # Revision 1.52  2007/03/12 21:17:05  rych
1092 # add server, serverinfo as arrays from config
1093 #
1094 # Revision 1.51  2007/03/09 14:31:47  tipaul
1095 # rel_3_0 moved to HEAD
1096 #
1097 # Revision 1.43.2.10  2007/02/09 17:17:56  hdl
1098 # Managing a little better database absence.
1099 # (preventing from BIG 550)
1100 #
1101 # Revision 1.43.2.9  2006/12/20 16:50:48  tipaul
1102 # improving "insecure" management
1103 #
1104 # WARNING KADOS :
1105 # you told me that you had some libraries with insecure=ON (behind a firewall).
1106 # In this commit, I created a "fake" user when insecure=ON. It has a fake branch. You may find better to have the 1st branch in branch table instead of a fake one.
1107 #
1108 # Revision 1.43.2.8  2006/12/19 16:48:16  alaurin
1109 # reident programs, and adding branchcode value in reserves
1110 #
1111 # Revision 1.43.2.7  2006/12/06 21:55:38  hdl
1112 # Adding ModZebrations for servers to get serverinfos in Context.pm
1113 # Using this function in rebuild_zebra.pl
1114 #
1115 # Revision 1.43.2.6  2006/11/24 21:18:31  kados
1116 # very minor changes, no functional ones, just comments, etc.
1117 #
1118 # Revision 1.43.2.5  2006/10/30 13:24:16  toins
1119 # fix some minor POD error.
1120 #
1121 # Revision 1.43.2.4  2006/10/12 21:42:49  hdl
1122 # Managing multiple zebra connections
1123 #
1124 # Revision 1.43.2.3  2006/10/11 14:27:26  tipaul
1125 # removing a warning
1126 #
1127 # Revision 1.43.2.2  2006/10/10 15:28:16  hdl
1128 # BUG FIXING : using database name in Zconn if defined and not hard coded value
1129 #
1130 # Revision 1.43.2.1  2006/10/06 13:47:28  toins
1131 # Synch with dev_week.
1132 #  /!\ WARNING :: Please now use the new version of koha.xml.
1133 #
1134 # Revision 1.18.2.5.2.14  2006/09/24 15:24:06  kados
1135 # remove Zebraauth routine, fold the functionality into Zconn
1136 # Zconn can now take several arguments ... this will probably
1137 # change soon as I'm not completely happy with the readability
1138 # of the current format ... see the POD for details.
1139 #
1140 # cleaning up Biblio.pm, removing unnecessary routines.
1141 #
1142 # DeleteBiblio - used to delete a biblio from zebra and koha tables
1143 #     -- checks to make sure there are no existing issues
1144 #     -- saves backups of biblio,biblioitems,items in deleted* tables
1145 #     -- does commit operation
1146 #
1147 # getRecord - used to retrieve one record from zebra in piggyback mode using biblionumber
1148 # brought back z3950_extended_services routine
1149 #
1150 # Lots of modifications to Context.pm, you can now store user and pass info for
1151 # multiple servers (for federated searching) using the <serverinfo> element.
1152 # I'll commit my koha.xml to demonstrate this or you can refer to the POD in
1153 # Context.pm (which I also expanded on).
1154 #
1155 # Revision 1.18.2.5.2.13  2006/08/10 02:10:21  kados
1156 # Turned warnings on, and running a search turned up lots of warnings.
1157 # Cleaned up those ...
1158 #
1159 # removed getitemtypes from Koha.pm (one in Search.pm looks newer)
1160 # removed itemcount from Biblio.pm
1161 #
1162 # made some local subs local with a _ prefix (as they were redefined
1163 # elsewhere)
1164 #
1165 # Add two new search subs to Search.pm the start of a new search API
1166 # that's a bit more scalable
1167 #
1168 # Revision 1.18.2.5.2.10  2006/07/21 17:50:51  kados
1169 # moving the *.properties files to intranetdir/etc dir
1170 #
1171 # Revision 1.18.2.5.2.9  2006/07/17 08:05:20  tipaul
1172 # there was a hardcoded link to /koha/etc/ I replaced it with intranetdir config value
1173 #
1174 # Revision 1.18.2.5.2.8  2006/07/11 12:20:37  kados
1175 # adding ccl and cql files ... Tumer, if you want to fit these into the
1176 # config file by all means do.
1177 #
1178 # Revision 1.18.2.5.2.7  2006/06/04 22:50:33  tgarip1957
1179 # We do not hard code cql2rpn conversion file in context.pm our koha.xml configuration file already describes the path for this file.
1180 # At cql searching we use method CQL not CQL2RPN as the cql2rpn conversion file is defined at server level
1181 #
1182 # Revision 1.18.2.5.2.6  2006/06/02 23:11:24  kados
1183 # Committing my working dev_week. It's been tested only with
1184 # searching, and there's quite a lot of config stuff to set up
1185 # beforehand. As things get closer to a release, we'll be making
1186 # some scripts to do it for us
1187 #
1188 # Revision 1.18.2.5.2.5  2006/05/28 18:49:12  tgarip1957
1189 # This is an unusual commit. The main purpose is a working model of Zebra on a modified rel2_2.
1190 # Any questions regarding these commits should be asked to Joshua Ferraro unless you are Joshua whom I'll report to
1191 #
1192 # Revision 1.36  2006/05/09 13:28:08  tipaul
1193 # adding the branchname and the librarian name in every page :
1194 # - modified userenv to add branchname
1195 # - modifier menus.inc to have the librarian name & userenv displayed on every page. they are in a librarian_information div.
1196 #
1197 # Revision 1.35  2006/04/13 08:40:11  plg
1198 # bug fixed: typo on Zconnauth name
1199 #
1200 # Revision 1.34  2006/04/10 21:40:23  tgarip1957
1201 # A new handler defined for zebra Zconnauth with read/write permission. Zconnauth should only be called in biblio.pm where write operations are. Use of this handler will break things unless koha.conf contains new variables:
1202 # zebradb=localhost
1203 # zebraport=<your port>
1204 # zebrauser=<username>
1205 # zebrapass=<password>
1206 #
1207 # The zebra.cfg file should read:
1208 # perm.anonymous:r
1209 # perm.username:rw
1210 # passw.c:<yourpasswordfile>
1211 #
1212 # Password file should be prepared with Apaches htpasswd utility in encrypted mode and should exist in a folder zebra.cfg can read
1213 #
1214 # Revision 1.33  2006/03/15 11:21:56  plg
1215 # bug fixed: utf-8 data where not displayed correctly in screens. Supposing
1216 # your data are truely utf-8 encoded in your database, they should be
1217 # correctly displayed. "set names 'UTF8'" on mysql connection (C4/Context.pm)
1218 # is mandatory and "binmode" to utf8 (C4/Interface/CGI/Output.pm) seemed to
1219 # converted data twice, so it was removed.
1220 #
1221 # Revision 1.32  2006/03/03 17:25:01  hdl
1222 # Bug fixing : a line missed a comment sign.
1223 #
1224 # Revision 1.31  2006/03/03 16:45:36  kados
1225 # Remove the search that tests the Zconn -- warning, still no fault
1226 # tollerance
1227 #
1228 # Revision 1.30  2006/02/22 00:56:59  kados
1229 # First go at a connection object for Zebra. You can now get a
1230 # connection object by doing:
1231 #
1232 # my $Zconn = C4::Context->Zconn;
1233 #
1234 # My initial tests indicate that as soon as your funcion ends
1235 # (ie, when you're done doing something) the connection will be
1236 # closed automatically. There may be some other way to make the
1237 # connection more stateful, I'm not sure...
1238 #
1239 # Local Variables:
1240 # tab-width: 4
1241 # End: