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