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